An in-depth analysis of PHP variable scopes _php tutorial

Source: Internet
Author: User
Tags parse error
Each variable in PHP has a scope for it, which is a field in which the variable can be accessed (thereby accessing its value). For starters, variables are scoped to the page where they reside. Therefore, if you define a $var, the rest of the page can access the $var, but other pages generally do not have access to it (unless special variables are used).

Because the Include files work as if they were part of the original (included) script, the variables defined before the include () line are available for the include file to use. In addition, variables defined within the include file can be used by the parent (including) script after the include () line.

When you use a function that you define yourself, all of this becomes less obvious. These functions have their own scopes, which means that variables used within a function cannot be used outside of them, and variables defined outside of a function cannot be used internally. For this reason, variables inside a function can have the same name as the variables outside it, but they are still completely different and have different values. For most junior programmers, this is a confusing concept.
To change the scope of a variable within a function, you can use the global statement.
Copy CodeThe 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, the $var inside the function is now the same as the $var outside the function. This means that the variable $var already has a value of 20, and if the value is changed inside the function, the external $var value will change.
Another way to avoid variable scopes is to take advantage of hyper-global variables: $_get, $_post, $_request, and so on. These variables are automatically accessible within your function (so they are super global variables). You can also add elements to the $GLOBALS array so that they can be used within the function.

In other words, it is best not to use global variables within a function. When designing functions, you should make them accept each value as an argument as needed, and return any value as needed. Relying on global variables within a function makes them more dependent on the context and therefore less useful.
The main variables in PHP are: Built-in super global variables, general variables, constants, global variables, static variables, and so on.

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

• Once a constant is declared, it can be globally visible, that is, they can be used inside and outside of the function, but this is limited to one page (including the PHP script that we included through include and include_once), but it is not available on other pages.
• Global variables declared in a script are visible throughout the script, but not inside the function, if the variables inside the function are the same as the global variable names, the variables inside the function prevail.
• When a variable used inside a function is declared as a global variable, its name is consistent with the name of the global variable, in which case we can use global variables outside of the function in the function so that the last one can be avoided because the variable inside the function is the same as the external global variable name, which overrides the external variable.
• A variable created inside a function that is declared static cannot be visible outside the function, but can be persisted during the execution of a function, most often in the process of recursive execution of a function.
• A variable created inside a function is local to the function, and when the function terminates, the variable does not exist.
The complete list of super global variables is as follows:
• $GOBALS all global variable arrays
.$_server Server environment variable array
.$_post Array of variables passed to the script via the POST method
.$_get An array of variables passed to the script by the GET method
.$_cookie array of COOKIE variables
.$_files array of variables related to file uploads
.$_env environment variable array
.$_request array of variables entered by all users includes input $_get $_post $_cookie
.$_session Session variable array
Example Explanation:
Copy CodeThe code is as follows:
Code highlighting produced by Actipro Codehighlighter (freeware) http://www.codehighlighter.com/--> $a = 4;
function Sendvalue ($x)
{
echo $x;
}
Sendvalue ($a);
?>

Explanation: $a defined in the function, the function defines the parameter, and when the function is called, the $a is passed in the form of a parameter. So the above code will work.
Copy CodeThe code is as follows:
Code highlighting produced by Actipro Codehighlighter (freeware) http://www.codehighlighter.com/--> $a = 4;
function Sendvalue ()
{
echo $a;
}
Sendvalue ();
?>

Explanation: When a function is called, $a cannot be passed as a parameter. So the above code does not work properly.
Variable Range
The scope of a variable is the context in which it is defined (translator: plainly, that is, its effective scope). Most PHP variables have a single range. This separate scope span also contains the files introduced by include and require. Example:
Copy CodeThe code is as follows:
$a = 1;
Include "B.inc";
?>

Here the variable $a will take effect in the include file B.inc. However, in a user-defined function, a local function scope is introduced. Any variables that are used inside the function will be limited to the local function in the default context. Example:
Copy CodeThe 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 refers to a local version of the variable $a, and within that range, it is not assigned a value. You may notice that the global variables in PHP are a little different from the C language, and in C, global variables are automatically applied in functions unless overridden by local variables. This can cause some problems, and some people may inadvertently change a global variable. A global variable in PHP must be declared global when used in a function.
The Global keyword
First, an example of using global:
Example 12-1. Using Global
Copy CodeThe 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 will be "3". The global variable $a and $b are declared in the function, and all reference variables of any variable are pointed to the global variable. 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 12-2. Replace Global with $GLOBALS
Copy CodeThe 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 $GLOBALS array, each variable is an element, the key name corresponds to the variable name, and the contents of the value variable. $GLOBALS exists globally because $GLOBALS is a hyper-global variable. The following example shows the usefulness of a hyper-global variable:
Example 12-3. Examples of hyper-global variables and scopes are shown
Copy CodeThe 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 scope, and they do not require a ' global ' statement. Superglobals was introduced in PHP 4.1.0.
Print $_post[' name '];
}
?>

Using static variables
Another important feature of the variable range is the static variable (variable). A static variable exists only in the local function domain, but its value is not lost when the program executes away from the scope. Take a look at the following example:
Example 12-4. Example of a static variable that needs to be shown
Copy CodeThe code is as follows:
Code highlighting produced by Actipro Codehighlighter (freeware) http://www.codehighlighter.com/--> function Test ()
{
$a = 0;
echo $a;
$a + +;
}
?>

This function is of little use because the value of $a is set to 0 and output "0" each time it is called. Adding a variable to the $a + + does not work because the variable $a does not exist once you exit the function. To write a count function that does not lose this count value, define the variable $a as static:
Example 12-5. Examples of using static variables
Copy CodeThe code is as follows:
Code highlighting produced by Actipro Codehighlighter (freeware) http://www.codehighlighter.com/--> function Test ()
{
static $a = 0;
echo $a;
$a + +;
}
?>

Now, each call to the Test () function outputs the value of the $a and adds one.
Static variables also provide a way to handle recursive functions. A recursive function is a function that calls itself. Be careful when writing recursive functions, because they can be recursive indefinitely. You must ensure that there is sufficient method to abort the recursion. This simple function recursively counts to 10, using a static variable $count to determine when to stop:
Example 12-6. static variables and recursive functions
Copy CodeThe 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 example above. If you assign a value to a declaration with the result of an expression, it causes a parse error.
Example 12-7. declaring static variables
Copy CodeThe 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;
}
?>

References to global and static variables
In the Zend engine 1 generation, the PHP4 was driven, and the static and global definitions for the variables were implemented in references 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:
Copy CodeThe 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);
?>

Performing the above example will result in the following output:
Copy CodeThe code is as follows:
Nullobject (StdClass) (0) {}

Similar behavior applies to static statements as well. References are not stored statically:
Copy CodeThe 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)) {
Assigning a reference 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)) {
Assigning 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 ();
?>

Performing the above example will result in the following output:
Copy CodeThe code is as follows:
Static object:nullstatic object:nullstatic object:nullstatic object:object (StdClass) (1) {[Property]]=> Int (1)}

The example above demonstrates 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.

http://www.bkjia.com/PHPjc/327377.html www.bkjia.com true http://www.bkjia.com/PHPjc/327377.html techarticle each variable in PHP has a scope for it, which is a field in which the variable can be accessed (thereby accessing its value). For beginners, the scope of the variable is ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.