A brief analysis of the scope of php variable

  • 2020-08-22 21:55:30
  • OfStack

Last night we had a problem with global variables in functions. Today I searched 1 and found a pretty good article about variable scope in php. It was translated by a netizen in this post 1:

Variable scope
The scope of a variable is the context in which it is defined. Most PHP variables have a single range. This separate scope span also contains the files introduced by include and require. Example:


<?php
$a = 1;
include "b.inc";
?>  

Here the variable $a will take effect in the include file b.inc. However, in user-defined functions, a range of local functions will be introduced. Any variables used within a function are by default restricted to the scope of a local function. Example:

<?php
$a = 1; /* global scope */
function Test()
{
   echo $a; /* reference to local scope variable */
}
Test();
?>  

This script does not have any output because the echo statement refers to a local version of the variable $a, and it is not assigned within this range. You may notice a slight difference between PHP's global variables and C's. In C, global variables automatically take effect in a function unless overridden by a local variable. This can cause problems, and some people may inadvertently change a global variable. In PHP, global variables must be declared global when used in a function.

The global keyword
First, an example using global:
Example 12-1. Use 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". The global variables $a and $b are declared in the function, and all references to any variable point to the global variable. There is no limit to the maximum number of global variables that a function can declare.

The second way to access variables globally is to customize the $GLOBALS array with the special PHP. The previous example can be written as:

Example 12-2. Use $GLOBALS instead of global


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

In the $GLOBALS array, each variable has one element, the key name corresponds to the variable name, and the value variable's contents. The reason $GLOBALS exists globally is because $GLOBALS is a super global variable. The following example shows the use of super global variables:

Examples 12-3. Examples of super global variables and scopes


<?php
function test_global()
{
   //  Most predefined variables do not  "super" They need to be used  'global'  Keywords to make them valid in the local area of the function. 
   global $HTTP_POST_VARS;
   print $HTTP_POST_VARS['name'];
   // Superglobals  They are valid in any range, they don't need to be  'global'  The statement. Superglobals  Is in the  PHP 4.1.0  The introduction of. 
   print $_POST['name'];
}
?>  

Using static variables
Another important feature of a variable scope is the static variable (static variable). A static variable exists only in a local function domain, but its value is not lost when the program execution leaves this scope. Take a look at this example:

Examples 12-4. Demonstrate an example that requires static variables


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

This function is useless because it sets the value of $a to 0 and prints "0" each time it is called. Adding $a++ to the variable 1 does not work, because $a does not exist once 1 exits the function. To write a counting function that does not lose the count value, define the variable $a to be static:

Examples 12-5. Examples using static variables


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

Now, each call to the Test() function outputs the value of $a and increments by 1.

Static variables also provide a way to handle recursive functions. A recursive function is a function that calls itself. Be careful when you write recursive functions, because it can go on forever. You must ensure that there are sufficient methods to abort the recursion. 1 This simple function recursively counts to 10, using the static variable $count to determine when to stop:

Examples 12-6. Static variables and recursive functions


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

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

Examples 12-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;
}
?>  

References to global and static variables
In the Zend engine 1 generation, PHP4 was driven and the static and global definitions for variables were implemented as references. For example, a true global variable imported within a function field using the global statement actually establishes a reference to the global variable. This can lead to unexpected behavior, as illustrated in the following examples:

<?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);
?>  

Executing the above example results in the following output:
NULLobject(stdClass)(0) {}
Similar behavior applies to the static statement. References are not statically stored:

<?php
$a = 1; /* global scope */
function Test()
{
   echo $a; /* reference to local scope variable */
}
Test();
?>  
0
Executing the above example results in the following output:
Static object: NULLStatic object: NULLStatic object: NULLStatic object: object(stdClass)(1) { ["property"]= > int(1)}

The above example demonstrates a second call when assigning a reference to a static variable & The get_instance_ref() function is not remembered.


Related articles: