Some problems on the scope of PHP variables _php skills

Source: Internet
Author: User
Tags parse error variable scope

Last night was a problem with a global variable in a function. Today, I searched for a pretty good article about the scope of variables in PHP. is a netizen translates 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 only a single range. This single range span also contains files introduced by include and require. Example:

Copy Code code as follows:

<?php
$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 range is introduced. Any variable that is used inside a function is limited by default to the scope of the local function. Example:
Copy Code code as follows:

<?php
$a = 1; /* Global Scope * *

function Test ()
{
echo $a; /* Reference to local scope variable * *
}

Test ();
?>


This script will not have any output because the Echo statement refers to a local version of the variable $a, and within that scope it is not assigned. You may notice that the global variable in PHP is a little bit different from the C language, in which the global variable takes effect automatically in the function unless overridden by a local variable. This can cause some problems, and some people may inadvertently 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. Using Global
Copy Code code as follows:

<?php
$a = 1;
$b = 2;

function Sum ()
{
Global $a, $b;

$b = $a + $b;
}

Sum ();
Echo $b;
?>


The output from 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 that a function can declare.

The second way to access a variable globally is to use a special PHP custom $GLOBALS array. The preceding example can be written as:

Example 12-2. Replace Global with $GLOBALS

Copy Code code as follows:

<?php
$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 the contents of the value variable. $GLOBALS exists globally because $GLOBALS is a super global variable. The following example shows the usefulness of a super global variable:

Example 12-3. Demonstrates examples of hyper-global variables and scopes

Copy Code code as follows:

<?php
function Test_global ()
{
Most predefined variables are not "super", and they need 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, they do not require a ' global ' declaration. Superglobals was introduced in the PHP 4.1.0.
Print $_post[' name '];
}
?>


using static variables
Another important feature of variable scope is static variable. A static variable exists only in a local function field, but its value is not lost when the program executes out of this scope. Take a look at the following example:

Example 12-4. Demo Example of needing static variables

Copy Code code as follows:

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

This function is not useful because the value of $a is set to 0 and output "0" each time it is invoked. Adding a variable $a + + does not work because the variable $a does not exist once the function is exited. To write a count function that does not lose the value of this count, define the variable $a as static:

Example 12-5. Examples of using static variables

Copy Code code as follows:

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

Now each call to the Test () function outputs the $a value 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, as you may be able to recursively go down indefinitely. There is a need to ensure that there are adequate methods to abort recursion. This simple function recursively counts to 10, using static variables $count to determine when to stop:

Example 12-6. static variables and recursive functions

Copy Code code as follows:

<?php
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 using the result of an expression, it can cause a parse error.

Example 12-7. declaring static variables

Copy Code code as follows:

<?php
function foo () {
static $int = 0; Correct
static $int = 1+2; Wrong (as it is a expression)
Static $int = sqrt (121); Wrong (as it is a expression too)

$int + +;
Echo $int;
}
?>


References to global and static variables
In the Zend engine 1 generation, the PHP4 is driven, and the static and global definitions of the variables are implemented in a references manner. For example, a real global variable imported within a function domain with the global statement actually establishes a reference to a global variable. This can lead to unexpected behavior, as demonstrated in the following example:
Copy Code code as follows:

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


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 Code code as follows:

<?php
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 previous example shows that when a reference is assigned to a static variable, the second time the &get_instance_ref () function is called, its value is not remembered.

Related Article

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.