An in-depth analysis of PHP variable scopes _php example

Source: Internet
Author: User
Tags parse error php script variable scope
Each variable in PHP has a scope for it, which is an area in which you can access a variable (and thus access 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 containing files work as if they were part of the original (included) script, the variables defined before the include () line are available to the containing file. In addition, the containing variables defined within the file can be used by the parent (included) script after that line of the include ().

When you use your own defined functions, all of these will become less obvious. These functions have their own scope, which means that variables used within a function cannot be used outside of them, and variables defined outside a function cannot be used internally. For this reason, a variable inside a function can have the same name as a variable outside it, 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 within a function, you can use the global statement.
Copy Code code as follows:

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, 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 this value is changed inside the function, the external $var value will also change.
Another way to circumvent variable scopes is to use hyper-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 $GLOBALS array so that you can use them within a 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.
In PHP, the main variables 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 these values in a PHP page, its value changes when used in other PHP pages.

• Constants once declared will be visible globally, that is, they can be used inside and outside of a function, but this is limited to a single page (including the PHP script we include 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, where the variables inside the function are the same as the global variable names, whichever is the variable within the function.
• Variables used inside a function are declared as global variables, the name is consistent with the name of the global variable, in which case we can use the global variable outside the function in the function, so that the last one is overridden because the variable inside the function has the same name as the external global variable.
• Variables created and declared as static inside a function cannot be visible outside of a function, but they can be persisted during multiple executions of a function, most commonly in the process of recursive execution of functions.
• The variables created inside the function are local to the function, and the variable does not exist when the function terminates.
The complete list of super global variables is as follows:
• $GOBALS all global variable arrays
.$_server Server Environment variables array
.$_post An array of variables passed through the POST method to the script
.$_get An array of variables passed to the script through the Get method
.$_cookie COOKIE Variable array
.$_files An array of variables associated with file uploads
.$_env environment variable array
.$_request All user-entered variable arrays include input from $_get $_post $_cookie
.$_session Session variable array
Example Explanation:
Copy Code code as follows:

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

Explanation: $a defined outside the function, the function defines the parameter, and when the function is invoked, the $a is passed as a parameter. So the code above can work correctly.
Copy Code code as follows:

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

Explanation: When a function is called, the $a cannot be passed as a parameter. So the above code does not work correctly.
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:

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 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:

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 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:

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 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:

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

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

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

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 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:

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 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:

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

Performing the above example will result in the following output:
Copy Code code as follows:

Nullobject (StdClass) (0) {}

Similar behavior applies to static statements as well. References are not stored statically:
Copy Code code as follows:

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

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.

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.