PHP's global variables are a little different from the C language: In C, global variables are automatically applied in functions unless overridden by local variables. This can cause some problems, and some people may accidentally change a global variable. As a result, global variables in PHP must be declared as globals when used in functions.
Take a look at the following example:
This script does not have any output, because the Echo statement refers to a local version of the variable $a, and within that range, it is not assigned a value.
Take a look at another example of using global:
Example #1 Use Global
The output of the above script will be "3". After you declare a global variable $a and $b in a function, all references to either variable point to its global version. PHP has no restrictions on the maximum number of global variables a function can declare.
The second way to access variables globally is to customize $GLOBALS arrays with special PHP. The previous example can be written as:
Example #2 Use $GLOBALS instead of global
$GLOBALS is an associative array, each variable is an element, the key name corresponds to the variable name, and the value corresponds to the contents of the variable. $GLOBALS exists globally because $GLOBALS is a hyper-global variable. The following example shows the usefulness of a hyper-global variable:
Example #3 Examples of hyper-global variables and scopes
references to global variables
Remember: If you assign a reference to a variable declared as global within a function, the reference is only visible inside the function.
In the Zend engine 1, it drives the PHP4, and the static and global definitions of variables are implemented in a reference manner. For example, a real global variable imported with a global statement inside a function field actually establishes a reference to a global variable. This may lead to unexpected behavior, as demonstrated in the following example:
The above routines will output:
Null
Object (StdClass) (0) {
}
Null is output for the first time because the global $var; is $var =& $GLOBALS [' var ']; The shorthand. Thus assigning other references to $var only changes the reference to the local variable $var.
That is to say $obj = &new stdclass; This statement changes the direction of the local variable $obj, and the effect of global $obj is already overwritten.
Similar behavior applies to static statements as well. References are not stored statically:
property++; return $obj;} function &get_instance_noref () { static $obj; Echo ' Static object: '; Var_dump ($obj); if (!isset ($obj)) { //assigns an object to a static variable $obj = new Stdclass; } $obj->property++; return $obj;} $obj 1 = get_instance_ref (), $still _obj1 = Get_instance_ref (); echo "\ n"; $obj 2 = Get_instance_noref (); $still _obj2 = get_ Instance_noref ();? >
The above routines will output:
Static Object:null
Static Object:null
Static Object:null
Static Object:object (StdClass) (1) {
["Property"]=>
Int (1)
}