Home > Backend Development > PHP Tutorial > PHP variable scope study notes sharing_PHP tutorial

PHP variable scope study notes sharing_PHP tutorial

WBOY
Release: 2016-07-13 10:50:25
Original
936 people have browsed it

Variable scope refers to whether a variable can be used with each other between pages and functions. What is its scope of action? Let me introduce some study notes of PHP variable usage scope to share with you.

The scope of variables in php is described in the php manual

In user-defined functions, a local function scope will be introduced. Any variables used inside a function will be restricted to the local function scope by default. For example:

The code is as follows Copy code
 代码如下 复制代码

$a = 1; /* global scope */

function Test()
{
echo $a; /* reference to local scope variable */
}

Test();
?>

$a = 1; /* global scope */

function Test()
{

echo $a; /* reference to local scope variable */

}

Test();
?>


This script will produce no output because the echo statement refers to a local version of the variable $a, and it is not assigned a value within this scope. You may have noticed that PHP’s global variables are a little different from C language. In C language, global variables automatically take effect in functions unless overridden by local variables. Let’s start with the above. Let me introduce it in detail below

Variables in PHP mainly include: built-in super global variables, general variables, constants, global variables, static variables, etc.

■Built-in super global variables can be used and visible anywhere in the script. That is, if we change one of the values ​​in a PHP page, its value will also change when used in other PHP pages.
■Constants once declared will be globally visible, that is, they can be used inside and outside functions, but this is only limited to one page (including PHP scripts we include through include and include_once), but in other pages Can no longer be used.
■Global variables declared in a script are visible throughout the script, but not inside the function. If the variable inside the function has the same name as the global variable, the variable inside the function shall prevail.
■When the variables used inside the function are declared as global variables, their names must be consistent with the names of the global variables. In this case, we can use the global variables outside the function in the function, so as to avoid the previous problem. The variable inside the function has the same name as the external global variable and overrides the external variable.
■Variables created and declared as static inside a function cannot be visible outside the function, but the value can be maintained during multiple executions of the function. The most common situation is during the recursive execution of the function.
■Variables created within a function are local to the function and cease to exist when the function terminates.
The complete list of super global variables is as follows:

■.$GOBALS Array of all global variables
■.$_SERVER server environment variable array

■.$_POST Array of variables passed to this script via the POST method

■.$_GET Array of variables passed to this script via the GET method

■.$_COOKIE cookie variable array
 代码如下 复制代码

$x=4;

function assignx(){

$x=0;

printf("$x inside function is %d
",$x);

}

assignx();

printf("$x outside of function is %d
",$x);

 
执行结果为

$ inside function is 0

$ outside of function is 4

■.$_FILES Array of variables related to file upload ■.$ENV environment variable array ■.$_REQUEST All user-input variable arrays include the input content contained in $_GET $_POST $_COOKIE ■.$_SESSION session variable array 1. Local variables A variable declared in a function is considered a local variable, that is, it can only be referenced within the function. If copied outside a function, it is considered a completely different variable (that is, different from the one contained in the function). Note that when you exit the function in which the variable was declared, the variable and its corresponding value are destroyed.
The code is as follows Copy code
$x=4; function assignx(){ $x=0; printf("$x inside function is %d
",$x); } assignx(); printf("$x outside of function is %d
",$x); The execution result is $ inside function is 0 $ outside of function is 4

2. Function parameters

PHP, like other programming languages, any function that accepts parameters must declare these parameters in the function header. Although these parameters (value parameters) accept values ​​from outside the function, they are no longer accessible after exiting the function.

The code is as follows Copy code
 代码如下 复制代码

function x10($value){
$value=

$value=$value*10

return $value;

}

function x10($value){

$value=

$value=$value*10

return $value;

}

Remember that although these function parameters can be accessed and manipulated within the function in which they are declared, the parameters will be destroyed when the function execution ends.
 代码如下 复制代码

 

$a = 1;
$b = 2;
function Sum()
{
$GLOBALS["b"] = $GLOBALS["a"] + $GLOBALS["b"];
}
Sum();
echo $b;
?>

3. Global variables

Global variables can be accessed anywhere in the program. However, in order to modify a global variable, it must be explicitly declared as a global variable in the function that modifies the variable. As long as the keyword GLOBAL is added in front of the variable, it is a global variable. If you put the GLOBA keyword in front of an existing variable, it tells PHP to use the variable with the same name.

 代码如下 复制代码

 

function test_global()
{
// 大多数的预定义变量并不 "super",它们需要用 'global' 关键字来使它们在函数的本地区域中有效。
global $HTTP_POST_VARS;
print $HTTP_POST_VARS['name'];
// Superglobals 在任何范围内都有效,它们并不需要 'global' 声明。Superglobals 是在 PHP 4.1.0 引入的。
print $_POST['name'];
}
?>

Use $GLOBALS instead of global

The code is as follows Copy code


$a = 1;

代码如下 复制代码

function Test ()
{
$a = 0;
echo $a;
$a++;
}
?>

$b = 2; function Sum() { $GLOBALS["b"] = $GLOBALS["a"] + $GLOBALS["b"]; } Sum(); echo $b; ?> In the $GLOBALS array, each variable is an element, the key name corresponds to the variable name, and the value variable content. $GLOBALS exists in the global scope because $GLOBALS is a superglobal variable. The following example shows the use of superglobal variables: Example 12-3. Example demonstrating superglobal variables and scope
The code is as follows Copy code
function test_global()<🎜> {<🎜> // Most predefined variables are not "super", they require the 'global' keyword to make them available in the local scope of the function. <🎜> global $HTTP_POST_VARS;<🎜> Print $HTTP_POST_VARS['name'];<🎜> // Superglobals are valid in any scope, they do not require a 'global' declaration. Superglobals were introduced in PHP 4.1.0. <🎜> Print $_POST['name'];<🎜> }<🎜> ?>
Use static variables Another important feature of variable scope is static variables. Static variables only exist in the local function scope, but their values ​​are not lost when program execution leaves this scope. Take a look at the example below: Example 12-4. Demonstrates the need for static variables
The code is as follows Copy code
function Test ()<🎜> {<🎜> $a = 0;<🎜> echo $a;<🎜> $a++;<🎜> }<🎜> ?>


This function is not very useful because it sets the value of $a to 0 and prints "0" every time it is called. $a++, which increments a variable by one, has no effect because the variable $a no longer exists once this function exits. To write a counting function that does not lose the current count value, define the variable $a as static:
Example 12-5. Example of using static variables

function Test()
{
static $a = 0;
echo $a;
$a++;
}
?>


Now, each call to the Test() function will output the value of $a and increment it by one.
Static variables also provide a way to handle recursive functions. A recursive function is a function that calls itself. Be careful when writing recursive functions, as they may recurse indefinitely. You must ensure that there are adequate ways to terminate recursion. Consider this simple function that recursively counts to 10, using the static variable $count to determine when to stop:
Example 12-6. Static variables and recursive functions

The code is as follows Copy code
 代码如下 复制代码

 

function Test()
{
static $count = 0;
$count++;
echo $count;
if ($count < 10) {
Test ();
}
$count--;
}
?>


function Test()

{
代码如下 复制代码

function foo(){
static $int = 0; // correct
static $int = 1+2; // wrong (as it is an expression)
static $int = sqrt(121); // wrong (as it is an expression too)
$int++;
echo $int;
}
?>

static $count = 0;

$count++; echo $count; if ($count < 10) {

Test ();

}
$count--;

}

?>


Note: Static variables can be declared as in the above example. Assigning it with the result of an expression in a declaration will result in a parsing error.

Example 12-7. Declare static variables
 代码如下 复制代码

 

$url = "www.bKjia.c0m";
function _DisplayUrl()
{
echo $url;
}
function DisplayUrl()
{
global $url;
echo $url;
}
_DisplayUrl();
DisplayUrl();
?> 

$url = "www.bKjia.c0m";
function _DisplayUrl()
{
echo $url;
}
function DisplayUrl()
{
global $url;
echo $url;
}
_DisplayUrl();
DisplayUrl();
?>

The code is as follows Copy code
function foo(){<🎜> static $int = 0; // correct<🎜> static $int = 1+2; // wrong (as it is an expression)<🎜> static $int = sqrt(121); // wrong (as it is an expression too)<🎜> $int++;<🎜> echo $int;<🎜> }<🎜> ?>
Note that a friend asked me about global static variables. There is no such thing as global variables in php php is an interpreted language. Although it has the static modifier, its meaning is completely different from that in .Net. Even if a variable in the class is declared static, this variable is only valid in the current page-level application domain. 2. Understand variable scope. Variables declared outside the method cannot be accessed within the method body. Such as:
The code is as follows Copy code
$url = "www.bKjia.c0m"; <🎜> function _DisplayUrl() <🎜> {  <🎜> echo $url; <🎜> }  <🎜> function DisplayUrl() <🎜> {  <🎜> global $url; <🎜> echo $url; <🎜> }  <🎜> _DisplayUrl(); <🎜> DisplayUrl(); <🎜> ?> $url = "www.bKjia.c0m";<🎜> function _DisplayUrl()<🎜> {<🎜> echo $url;<🎜> }<🎜> function DisplayUrl()<🎜> {<🎜> global $url;<🎜> echo $url;<🎜> }<🎜> _DisplayUrl();<🎜> DisplayUrl();<🎜> ?>
The

_DisplayUrl method will not display any results because the variable $url is inaccessible in the method body _DisplayUrl. Just add global before $url, such as the DisplayUrl method.

Global variables defined in the method body can be accessed outside the method:

The code is as follows
 代码如下 复制代码


function _DisplayUrl()
{
global $myName;
$myName='yibin';
}

_DisplayUrl();
echo $myName; //output yibin
?> 

Copy code

function _DisplayUrl()

global $myName;
        $myName='yibin';                                                  } 
         
_DisplayUrl();
echo $myName; //output yibin
?>

http://www.bkjia.com/PHPjc/632648.htmlwww.bkjia.comtrue
http: //www.bkjia.com/PHPjc/632648.html
TechArticle
Variable scope is whether a variable can be used with each other between the page and the function. What is its scope? The editor below will introduce to you some study notes on the use of php variables...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template