This article provides a detailed analysis of the scope of php variables. For more information, see the scope of each variable in PHP, it refers to a field in which variables can be accessed (and thus its value can be accessed. For beginners, the scope of variables is the page where they reside. Therefore, if you define $ var, the rest of the page can access $ var, but other pages generally cannot access it (unless special variables are used ).
Because the inclusion files work as they are part of the original (include) script, the variables defined before the include () line are available for the Inclusion file. In addition, the variables defined in the include file can be used by the parent (include) script after the line include.
When you use a function defined by yourself, all of this will become less obvious. These functions have their own scopes, which means that the variables used in a function cannot be used outside the function, and the variables defined outside the function cannot be used inside the function. For this reason, the internal variables of the function can have the same name as the external variables, but they are still completely different variables and have different values. For most junior programmers, This is a confusing concept.
To change the scope of a variable in a function, use the global statement.
The Code is as follows:
Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/--> 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. If this value is changed inside the function, the external $ var value will also change.
Another way to avoid variable scopes is to use super-global variables such as $ _ GET, $ _ POST, and $ _ REQUEST. These variables are automatically accessible in your function (therefore, they are super global variables ). You can also add elements to the $ GLOBALS array so that they can be used in the function.
In other words, it is best not to use global variables in functions. When designing functions, make them accept each value as a parameter as needed and return any value as needed. Relying on the global variables in the function makes them more context-dependent and thus less useful.
In PHP, variables mainly include: built-in Super global variables, General 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 a value in a PHP page, the value will also change when used on other PHP pages.
• Once declared, constants can be globally visible, that is, they can be used inside and outside the function, but this is limited to PHP scripts included in a page (including include and include_once, but it cannot be used in other pages.
• The global variables declared in a script are visible throughout the script, but not inside the function. If the variables in the function are the same as the global variables, take the internal variables of the function as the standard.
• When the variables used in the function are declared as global variables, their names must be consistent with those of global variables. In this case, we can use global variables outside the function, in this way, we can avoid the situation where the external variables are overwritten because the internal variables of the function are the same as the external global variables.
• A variable created and declared as static within a function cannot be visible outside the function, but this value can be kept during multiple function executions, the most common case is the Recursive Execution of functions.
• The variable created in the function is local to the function, and does not exist when the function is terminated.
The complete list of super global variables is as follows:
•. $ GOBALS all global variable Arrays
•. $ _ SERVER environment variable array
•. $ _ POST the variable array passed to the script through the POST Method
•. $ _ GET the variable array passed to the script through the GET Method
•. $ _ COOKIE cookie variable array
•. $ _ FILES variable array related to File Upload
•. $ _ ENV Environment variable array
•. $ _ REQUEST all user input variable arrays include $ _ GET $ _ POST $ _ input content contained in COOKIE
•. $ _ SESSION variable array
Example:
The Code is as follows:
Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/--> $ A = 4;
Function sendValue ($ x)
{
Echo $ x;
}
SendValue ($ );
?>
Description: $ a is defined outside the function. a function defines parameters. When a function is called, $ a is passed as a parameter. Therefore, the above Code can run normally.
The Code is as follows:
Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/--> $ A = 4;
Function sendValue ()
{
Echo $;
}
SendValue ();
?>
Description: When a function is called, $ a cannot be passed as a parameter. Therefore, the above Code cannot run normally.
Variable range
The scope of a variable is the context defined by it ). Most PHP variables have only one separate range. This separate range span also contains the files introduced by include and require. Example:
The Code is as follows:
$ A = 1;
Include "B. inc ";
?>
The variable $ a will take effect in the included file B. inc. However, in user-defined functions, a local function range will be introduced. By default, any variable used in a function is limited to a local function. Example:
The Code is as follows:
Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/--> $ 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 references a local version of variable $ a and is not assigned a value within this range. You may notice that the global variables in PHP are a little different from those in C language. In C language, global variables automatically take effect in functions unless they are overwritten by local variables. This may cause some problems. Some may carelessly change a global variable. Global variables in PHP must be declared as global when used in functions.
The global keyword
First, an example of using global:
Example 12-1. Use global
The Code is as follows:
Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/--> $ A = 1;
$ B = 2;
Function Sum ()
{
Global $ a, $ B;
$ B = $ a + $ B;
}
Sum ();
Echo $ B;
?>
The output of the above script is "3 ". Specify the global variables $ a and $ B in the function. All referenced variables of any variable point to the global variable. PHP has no limit on the maximum number of global variables that a function can declare.
The second way to access variables globally is to use a special PHP custom $ GLOBALS array. The preceding example can be written as follows:
Example 12-2. replace global with $ GLOBALS
The Code is as follows:
Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/--> $ A = 1;
$ 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 value variable content. $ GLOBALS exists globally because $ GLOBALS is a super global variable. The following example shows how to use a super global variable:
Example 12-3. Examples of hyperglobal variables and scopes
The Code is as follows:
Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/--> Function test_global ()
{
// Most of the predefined variables are not "super". They need to use the 'global' keyword to make them valid in the local area of the function.
Global $ HTTP_POST_VARS;
Print $ HTTP_POST_VARS ['name'];
// Superglobals are valid in any range and they do not require 'global' declarations. Superglobals was introduced in PHP 4.1.0.
Print $ _ POST ['name'];
}
?>
Use static variables
Another important feature of variable range is static variable ). Static variables only exist in local function domains, but their values are not lost when the program runs out of this scope. Take a look at the following example:
Example 12-4. Example of static variables
The Code is as follows:
Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/--> Function Test ()
{
$ A = 0;
Echo $;
$ A ++;
}
?>
This function is useless, because every call will set the value of $ a to 0 and output "0 ". Adding $ a ++ to the variable does not work, because $ a does not exist once you exit this function. To write a counting function that does not lose the current Count value, you must define variable $ a as static:
Example 12-5. Example of using static variables
The Code is as follows:
Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/--> Function Test ()
{
Static $ a = 0;
Echo $;
$ A ++;
}
?>
Now, every time you call the Test () function, the value of $ a is output and added with one.
Static variables also provide a method for processing recursive functions. A recursive function is a function that calls itself. Be careful when writing recursive functions, because infinite recursion may occur. Make sure there are sufficient methods to abort recursion. The simple function calculates 10 recursively and uses the static variable $ count to determine when to stop:
Example 12-6. Static variables and recursive functions
The Code is as follows:
Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/--> Function Test ()
{
Static $ count = 0;
$ Count ++;
Echo $ count;
If ($ count <10 ){
Test ();
}
$ Count --;
}
?>
Note: static variables can be declared according to the preceding example. If a value is assigned to the expression result in the declaration, the parsing error occurs.
Example 12-7. declare static variables
The Code is as follows:
Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/--> 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;
}
?>
Reference of global and static variables
In the first generation of the Zend engine, PHP4 is driven. The static and global definitions of variables are implemented in the form of references. For example, a real global variable imported using a global statement within a function domain is actually a reference to a global variable. This may lead to unexpected behaviors, as demonstrated in the following example:
The Code is as follows:
Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/--> 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 preceding example will result in the following output:
The Code is as follows:
NULLobject (stdClass) (0 ){}
Similar behavior applies to static statements. References are not stored statically:
The Code is as follows:
Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/--> Function & get_instance_ref (){
Static $ obj;
Echo "Static object :";
Var_dump ($ obj );
If (! Isset ($ obj )){
// Assign a reference value to a static variable
$ Obj = & new stdclass;
}
$ Obj-> property ++;
Return $ obj;
}
Function & get_instance_noref (){
Static $ obj;
Echo "Static object :";
Var_dump ($ obj );
If (! Isset ($ obj )){
// Assign an object 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 preceding example will result in the following output:
The Code is as follows:
Static object: NULLStatic object: object (stdClass) (1) {["property"] => int (1 )}
The preceding example shows that when a reference is assigned to a static variable, the value of the second call to the & get_instance_ref () function is not remembered.