In depth analysis of the SCOPE of the php variable

  • 2020-06-03 06:12:28
  • OfStack

Each variable in PHP has a scope for it, which is the domain in which the variable (and thus its value) can be accessed. For starters, the scope of variables is the page on which they reside. Therefore, if you define $var, the rest of the page can be accessed to $var, but no other page 1 can access it (unless using special variables).

Because the include files work as if they were part 1 of the original (include) script, the variables defined before the include() line 1 are available for the include file. In addition, variables defined in the include file can be used by the parent (include) script after that 1 line of include().

All of this becomes less obvious when you use your own defined functions. These functions have their own scope, which means that variables used within a function cannot be used outside of it, and variables defined outside a function cannot be used within it. For this reason, variables inside a function can have the same name as those outside, but they are still completely different variables and have different values. To most junior programmers, this is a confusing concept.
To change the scope of a variable within a function, use the global statement.

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--><?php
function function_name() {
    global $var;
}
$var=20;
function_name(); // Function call.
?>

In this example, $var inside the function is now the same as $var outside the function. This means that the variable $var already has a value of 20, and if you change this value inside the function, the external $var value will also change.
Another way to avoid variable scope is to use super global variables: $_GET, $_POST, $_REQUEST, and so on. These variables are automatically accessible within your function (therefore, they are super global variables). You can also add elements to the $GLOBALS array to make them available within functions.

That is, it is best not to use global variables within functions. When you design functions, you should make them take each value as an argument as needed and return any value as needed. Relying on global variables within a function makes them more context-dependent and therefore less useful.
In PHP, variables mainly include: built-in super global variables, 1-like variables, constants, global variables, static variables and so on.

The built-in super global variables can be used and visible anywhere in the script. That is, if we change one value in one PHP page, its value will change when used in other PHP pages.

The & # 8226; Once constants 1 are declared they will be globally visible, that is, they can be used inside and outside functions, but this is limited to the PHP scripts that are included in one page (including include and include_once), but not in other pages.
The & # 8226; A global variable declared in 1 script is visible throughout the script, but not inside the function. Variables inside the function that have the same name as the global variable are subject to the variables inside the function.
The & # 8226; Function of internal use global variables for variable declarations, the name and the name of a global variable to 1, in this case, we can use in the function function outside of the global variable, so you can avoid one as function of internal and external global variable names and cover the same external variables.
The & # 8226; Variables that are created and declared static inside a function cannot be seen outside of the function, but they can be retained during multiple executions of the function, most often during recursive execution of the function.
The & # 8226; A variable created inside a function is local to the function, and when the function terminates, the variable does not exist.
The full list of super global variables is as follows:
The & # 8226; $GOBALS array of all global variables
The & # 8226; .$_SERVER array of server environment variables
The & # 8226; .$_POST is the array of variables passed to the script by the POST method
The & # 8226; .$_GET passes the array of variables to the script via the GET method
The & # 8226; .$_COOKIE cookie variable array
The & # 8226; .$_FILES array of variables associated with file uploads
The & # 8226; .$_ENV array of environment variables
The & # 8226; .$_REQUEST The array of variables entered by all users includes the input contained in $_GET $_POST $_COOKIE
The & # 8226; .$_SESSION array of session variables
Example explanation:

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--><?php 
   $a = 4;
   function sendValue($x)
     {
        echo $x;
     }
    sendValue($a);
?>

$a is defined outside of the function. The function defines an argument, and when the function is called, $a is passed as an argument. So the above code works fine.

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--><?php 
    $a = 4;
    function sendValue()
     {
       echo $a;
    }
    sendValue();
?>

Explanation: $a cannot be passed as an argument when a function is called. So the above code doesn't work properly.
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:

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--><?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 THE C language, where 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

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--><?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

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--><?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 contents of the value variable. $GLOBALS exists globally 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

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--><?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 variable ranges is static variables (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

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--><?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 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

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--><?php
function Test()
{
   static $a = 0;
   echo $a;
   $a++;
}
?>

Each call to the Test() function now prints the value of $a and adds 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

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--><?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

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--><?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, PHP4 was driven, and the static and global definitions for variables were implemented in references fashion. 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 demonstrated in the following examples:

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--><?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:

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--><?php
function &get_instance_ref() {
   static $obj;
   echo "Static object: ";
   var_dump($obj);
   if (!isset($obj)) {
   //  will 1 Five references are assigned to static variables 
   $obj = &new stdclass;
   }
   $obj->property++;
   return $obj;
}
function &get_instance_noref() {
   static $obj;
   echo "Static object: ";
   var_dump($obj);
   if (!isset($obj)) {
   //  will 1 Object assigned to a static variable 
   $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();
?>

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: