An analysis of some problems in the scope of PHP variables _php tutorial

Source: Internet
Author: User
Last night with this problem, is the global variable in the function of the problem. Search today, found a pretty good article, the scope of the variable in PHP. is a netizen translated in this post:

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 the Code code 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 the Code code as follows:
$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 the Code code as follows:
$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 the Code code as follows:
$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 the Code code as follows:
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 the Code code as follows:
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 the Code code as follows:
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 the Code code as follows:
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 the Code code as follows:
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 the Code code as follows:
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:
Nullobject (StdClass) (0) {}
Similar behavior applies to static statements as well. References are not stored statically:
Copy the Code code as follows:
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:
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/328128.html www.bkjia.com true http://www.bkjia.com/PHPjc/328128.html techarticle last night With this problem, is the global variable in the function of the problem. Search today, found a pretty good article, the scope of the variable in PHP. is a netizen ...

  • 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.