PHP Variable Scope learning Note sharing _php Tutorial

Source: Internet
Author: User
Tags parse error variable scope
Variable scope is a variable between the page and function can use each other, its scope of action, the following small series to introduce you to the PHP variable using the domain of some learning notes to get out and exchange with you.

The scope of the variables in PHP is described in the PHP manual

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. For example:

The code is as follows Copy Code

$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, in the C language, the global variables automatically take effect in the function, unless overridden by a local variable, the above, I come to detail


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.
constants, once declared, can be globally visible, that is, they can be used inside and outside the function, but this is limited to a single page (containing the PHP script that we included through include and include_once), but it is not available on other pages.
The 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 the same as 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 that is created inside a function and declared as static cannot be visible outside the function, but it can be persisted during the execution of a function many times, most commonly in the 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 an array of environment variables
.$_request array of variables entered by all users includes input $_get $_post $_cookie
.$_session Session Variable Array


1. Local Variables

A variable declared in a function is considered a local variable, that is, it can only be referenced in that function. If you copy outside of a function, it is considered to be another variable that is completely different (that is, different from the one contained in the function). Note that when you exit a function that declares a variable, the variable and its corresponding value are revoked.

The code is as follows Copy Code

$x = 4;

function Assignx () {

$x = 0;

printf ("$x inside function is%d
", $x);

}

Assignx ();

printf ("$x outside of function is%d
", $x);


Execution results are

$ inside function is 0

$ Outside of function is 4

2. Function parameters

As with other programming languages, any function that accepts parameters must declare them in the first part of the functions. Although these parameters (value parameters) accept values outside the function, they are no longer accessible after exiting the function.

The code is as follows Copy Code

function x10 ($value) {
$value =

$value = $value *10

return $value;

}

Remember, although these function parameters can be accessed and contributed within the function that declares the arguments, the parameters are revoked when the function is executed.

3. Global variables

Global variables can be accessed from anywhere in the program. However, in order to modify a global variable, you must explicitly declare it as a global variable in a function that modifies the variable. Just precede the variable with the keyword global, which is the global variable. If you put the Globa keyword in front of an existing variable, you tell PHP to use a variable of the same name.


Replace Global with $GLOBALS

The code is as follows Copy Code

$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

The code is as follows Copy Code

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

The code is as follows Copy Code

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

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

The code is as follows Copy Code

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

The code is as follows Copy Code

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

Note that a friend asked me global static variables , there is no global variable in PHP this said live

PHP is an interpreted language, although there are static modifiers, but meaning with. NET is completely different.
Even if a variable in the class is declared static, the variable is only valid in the application domain at the current page level.

2. Understand the scope of variables.

Variables declared outside the method body are not accessible within the method body.
Such as:

copy code

"!--? php
$url = "Www.bKji A.c0m ";
Function _displayurl ()
{
echo $url;
}
Function Displayurl ()
{
Global $url;
Echo $url;
}
_displayurl ();
Displayurl ();
?>

!--? php
$url = "www.bKjia.c0m";
Function _displayurl ()
{
echo $url;
}
Function Displayurl ()
{
Global $url;
echo $url;
}
_displayurl ();
Displayurl ();
?

The _displayurl method does not show any results because the variable, the _displayurl, is inaccessible in the method body, and global can be added to the prefix, such as the Displayurl method.

The global variables defined in the method body can be accessed outside the method body:

The code is as follows Copy Code


function _displayurl ()
{
Global $myName;
$myName = ' Yibin ';
}

_displayurl ();
Echo $myName; Output Yibin
?>

http://www.bkjia.com/PHPjc/632648.html www.bkjia.com true http://www.bkjia.com/PHPjc/632648.html techarticle variable scope is a variable between the page and function can use each other, its scope of action, the following small series to introduce you to the PHP variable using the domain of some learning notes ...

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