PHP variable Scope

Source: Internet
Author: User
Tags php script variable scope

Excerpt from: http://www.qianyunlai.com.com/blog/220.html

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.


? 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. A global variable declared in a script is visible throughout the script, but not inside the function, where the variable within the function is the same as the global variable name, whichever is the variable within the function. When a variable used inside a function is declared as a global variable, 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. A variable that is created and declared static inside a function cannot be visible outside of a function, but it can be persisted during multiple executions of a function, most commonly in the process of recursive execution of a function. A variable created inside a function is 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 an array of all global variables. An array of $_server server environment variables. $_post An array of variables passed to the script by the POST method. $_get An array of variables passed to the script by the Get method. $_ An array of cookie cookie variables. $_files An array of variables related to file uploads. An array of $_ENV environment variables. $_request All user-entered variable arrays include input that is contained in $_get $_post $_cookie. $_session session Variable array

Example Explanation:

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

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

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

? 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

? 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

? 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

  Code PHP
Function  test_global ()
{
   //  Most predefined variables are not   "super". They need to use the   ' global '   keywords to make them valid in the local area of the function.
    Global   $HTTP _post_vars;

    Print   $HTTP _post_vars [' name '];

   // Superglobals  is valid in any scope, they do not need   ' global '   statement. The superglobals  was introduced in  PHP 4.1.0 .
    print   $_post [' name '];
}
?>  

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.