The scope of a variable is the context in which it is defined (that is, its effective scope). Most PHP variables have only a single scope. This single scope span also includes files introduced by include and require . For example:
<?php $a = 1; include 'b.inc'; ?>
This variable $a will take effect in the include file b.inc. However, 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:
<?php $a = 1; /* global scope */ function Test() { echo $a; /* reference to local scope variable */ } Test(); ?>
This script will not produce any output because the echo statement refers to a local version of the variable $a, and it is not assigned a value in this scope. You may notice 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. This may cause some problems, someone may accidentally change a global variable. Global variables in PHP must be declared global when used in functions.
global keyword
First, an example of using global:
Example #1 Using global
<?php $a = 1; $b = 2; function Sum() { global $a, $b; $b = $a + $b; } Sum(); echo $b; ?>
The output of the above script will be "3". After global variables $a and $b are declared in a function, all references to either variable point to its global version. PHP has no limit on the maximum number of global variables that a function can declare.
The second way to access variables in the global scope is to use special PHP custom $GLOBALS array. The previous example can be written as:
Example #2 Use $GLOBALS instead of global
<?php $a = 1; $b = 2; function Sum() { $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b']; } Sum(); echo $b; ?>
$GLOBALS is an associative array, each variable is an element, the key name corresponds to the variable name, and the value corresponds to the content of the variable. $GLOBALS exists in the global scope because $GLOBALS is a superglobal variable. The following example shows the usefulness of superglobal variables:
Example #3 Example demonstrating superglobal variables and scope
<?php function test_global() { // 大多数的预定义变量并不 "super",它们需要用 'global' 关键字来使它们在函数的本地区域中有效。 global $HTTP_POST_VARS; echo $HTTP_POST_VARS['name']; // Superglobals 在任何范围内都有效,它们并不需要 'global' 声明。Superglobals 是在 PHP 4.1.0 引入的。 echo $_POST['name']; } ?>
Using 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 following example:
Example #4 Demonstrates an example that requires a static variable
<?php function Test() { $a = 0; echo $a; $a++; } ?>
This function is not very useful because it will set the value of $a to 0 and output 0 every time it is called. $a++, which increments the variable by one, has no effect because the variable $a no longer exists once the function exits. To write a counting function that will not lose the current count value, define the variable $a as static:
Example #5 Example of using static variables
<?php function test() { static $a = 0; echo $a; $a++; } ?>
Now, the variable $a is only used when test( is called for the first time ) function is initialized, and every time the test() function is called thereafter, the value of $a will be output and incremented by one.
Static variables also provide a way to deal with 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 means to terminate recursion. The following simple function recursively counts to 10, using the static variable $count to determine when to stop:
Example #6 Static variables and recursive functions
<?php function test() { static $count = 0; $count++; echo $count; if ($count < 10) { test(); } $count--; } ?>
Static variables can be declared as in the example above. Assigning it with the result of an expression in a declaration will result in a parsing error.
Example #7 Declare static variables
<?php 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 declarations are resolved at compile time.
There is nothing wrong with using the global keyword outside of a function. Can be used when including files within a function.
References to global and static variables
In Zend engine 1 generation, which drives PHP4, static and global definitions of variables are implemented in the form of references. For example, a true global variable imported with the global statement inside a function scope actually establishes a reference to the global variable. This may lead to unexpected behavior, as demonstrated in the following example:
<?php function test_global_ref() { global $obj; $obj = &new stdclass; } function test_global_noref() { global $obj; $obj = new stdclass; } test_global_ref(); var_dump($obj); test_global_noref(); var_dump($obj); ?>
The above routine will output:
NULL
object(stdClass)(0) {}
Similar behavior also applies to static statements . References are not stored statically:
<?php function &get_instance_ref() { static $obj; echo 'Static object: '; var_dump($obj); if (!isset($obj)) { // 将一个引用赋值给静态变量 $obj = &new stdclass; } $obj->property++; return $obj; } function &get_instance_noref() { static $obj; echo 'Static object: '; var_dump($obj); if (!isset($obj)) { // 将一个对象赋值给静态变量 $obj = new stdclass; } $obj->property++; return $obj; } $obj1 = get_instance_ref(); $still_obj1 = get_instance_ref(); echo "\n"; $obj2 = get_instance_noref(); $still_obj2 = get_instance_noref(); ?>
The above routine will output:
Static object: NULL Static object: NULL Static object: NULL Static object: object(stdClass)(1) { ["property"]=>int(1) }
The above example demonstrates that when a reference is assigned to a static variable, its value is not remembered the second time the &get_instance_ref() function is called. live.