Php variable scope

Source: Internet
Author: User
From: every variable in www.qianyunlai.com.comblog220.html PHP has a scope for it. It refers to a field in which variables can be accessed (and thus accessed. For beginners, the scope of variables is the page where they reside. Therefore, if you define $ var, the rest of the page

From: every variable in http://www.qianyunlai.com.com/blog/220.html PHP has a domain for it, which is a field where variables can be accessed (and thus accessed. For beginners, the fields of variables are the pages on which they reside. Therefore, if you define $ var, the rest of the page

From: http://www.qianyunlai.com.com/blog/220.html

In PHPVariableEach hasFunctionDomain.Variable(To access its value. For beginners,VariableOfFunctionThe domain is the page on which they reside. Therefore, if you define $ var, the rest of the page can access $ var, but other pages generally cannot access it (unless you use a specialVariable).
Because the include files work as they are part of the original (include) script, they are defined before the include () line.VariableAvailable for inclusion files. In addition, includeVariableIt can be used by the parent (include) script after the include () line.
When you use a function defined by yourself, all of this will become less obvious. These functions have their ownFunctionThis means thatVariableIt cannot be used outside of a function.VariableIt cannot be used internally. For this reasonVariableCan have externalVariableSame name, but they are still completely differentVariableAnd has different values. For most junior programmers, This is a confusing concept.
To changeVariableOfFunctionDomain. You can use the global statement.


Function function_name (){
Global $ var;
}
$ Var = 20;
Function_name (); // Function call.
?>

In this example, $ var inside the function is now the same as $ var outside the function. This meansVariable$ Var already has a value of 20. If this value is changed inside the function, the external $ var value also changes.
AvoidVariableFunctionAnother method of the domain is to use the hyper-GlobalVariable: $ _ GET, $ _ POST, and $ _ REQUEST. TheseVariableAutomatically accessible in your function (therefore, they are ultra-Global)Variable). You can also add elements to the $ GLOBALS array so that they can be used in the function.
That is to say, it is best not to use global functions.Variable. When designing functions, make them accept each value as a parameter as needed and return any value as needed. Depends on the global functionVariableWill make them more dependent on the context, so it is not very useful.




  In PHPVariableMainly include: built-in Super globalVariable, AverageVariable, Constant, globalVariable, StaticVariableAnd so on.
Built-in Super globalVariableIt can be used and visible anywhere in the script. That is, if we change a value in a PHP page, the value will also change when used on other PHP pages.

  • Once declared, constants can be globally visible, that is, they can be used inside and outside the function, but this is limited to the PHP scripts included in a page (including include and include_once, but it cannot be used in other pages.
  • Global declared in a scriptVariableIt is visible in the entire script, but not inside the function.VariableIfVariableThe name is the same.Variable.
  • TheVariableDeclared as globalVariableThe name must be globalVariableIn this case, we can use the globalVariableIn this way, we can avoid the previousVariableGlobalVariableThe same name overwrites the externalVariableThis is the case.
  • Create and declare a staticVariableIt cannot be visible outside the function, but it can be maintained during multiple execution of the function. The most common situation is the Recursive Execution of the function.
  • TheVariableThe function is local, and when the function is terminatedVariableIt does not exist.

Super globalVariableThe complete list:

  • . $ GOBALS all globalVariableArray
  • . $ _ SERVER environmentVariableArray
  • . $ _ POST passed to the script through the POST MethodVariableArray
  • . $ _ GET passed to the script through the GET MethodVariableArray
  • . $ _ COOKIEVariableArray
  • . $ _ FILES related to File UploadVariableArray
  • . $ _ ENV EnvironmentVariableArray
  • . $ _ REQUESTVariableArray includes $ _ GET $ _ POST $ _ input content contained in COOKIE
  • . $ _ SESSIONVariableArray

Example:

Explanation:$ A is defined outside the function. a function defines parameters. When a function is called, $ a is passed as a parameter. Therefore, the above Code can run normally.

Explanation:When a function is called, $ a cannot be passed as a parameter. Therefore, the above Code cannot run normally.

VariableRange
VariableIt defines the context ). Most PHPVariableThere is only one separate range. This separate range span also contains the files introduced by include and require. Example:

$ A = 1;
Include "B. inc ";
?>

HereVariable$ A will take effect in the included file B. inc. However, in user-defined functions, a local function range will be introduced. AnyVariableBy default, it is restricted to the range of local functions. Example:

$ 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 references a local versionVariable$ A, and in this range, it is not assigned a value. You may have noticed the global structure of PHP.VariableIt is a little different from C. In CVariableAutomatically takes effect in the function unless it isVariableOverwrite. This may cause some problems. Some may carelessly change the overall situation.Variable. Global in PHPVariableWhen using a function, it must be declared as global.

The global keyword
First, an example of using global:

Example 12-1. Use global

$ A = 1;
$ B = 2;

Function Sum ()
{
Global $ a, $ B;

$ B = $ a + $ B;
}

Sum ();
Echo $ B;
?>


The output of the above script is "3 ". Specify global in the functionVariable$ A and $ B, anyVariableAll referencesVariableAll point to the globalVariable. Global declarations of a functionVariablePHP is not limited.

Global AccessVariableThe second method is to use a special PHP custom $ GLOBALS array. The preceding example can be written as follows:

Example 12-2. replace global with $ GLOBALS

$ A = 1;
$ B = 2;

Function Sum ()
{
$ GLOBALS ["B"] = $ GLOBALS ["a"] + $ GLOBALS ["B"];
}

Sum ();
Echo $ B;
?>


In the $ GLOBALS arrayVariableIs an element, and the key name correspondsVariableName, ValueVariable. $ GLOBALS exists globally because $ GLOBALS is a super globalVariable. The following example shows the globalVariableUsage:

Example 12-3. Demonstrate the hyper-GlobalVariableAndFunctionDomain example

Code

Function test_global ()
{
// Most predefined valuesVariableNot "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 range and they do not require 'global' declarations. Superglobals was introduced in PHP 4.1.0.
Print $ _ POST ['name'];
}
?>

Use staticVariable
VariableAnother important feature of range is staticVariable(Static variable ). StaticVariableOnly exists in the local function domain, but when the program runs out of thisFunctionThe value is not lost. Take a look at the following example:

Example 12-4. Demonstrate staticVariableExample

Function Test ()
{
$ A = 0;
Echo $;
$ A ++;
}
?>



This function is useless, because every call will set the value of $ a to 0 and output "0 ". SetVariable$ A ++ with a plus sign does not exist.FunctionBecause once you exit this functionVariable$ A does not exist. To write a counting function that does not lose the current Count value, SetVariable$ A is static:

Example 12-5. Use staticVariableExample

Function Test ()
{
Static $ a = 0;
Echo $;
$ A ++;
}
?>


Now, every time you call the Test () function, the value of $ a is output and added with one.

StaticVariableIt also provides a method for processing recursive functions. A recursive function is a function that calls itself. Be careful when writing recursive functions, because infinite recursion may occur. Make sure there are sufficient methods to abort recursion. This simple function calculates 10 recursively and uses staticVariable$ Count to determine when to stop:

Example 12-6. StaticVariableAnd recursive functions

Function Test ()
{
Static $ count = 0;

$ Count ++;
Echo $ count;
If ($ count <10 ){
Test ();
}
$ Count --;
}
?>


Note: staticVariableYou can declare it according to the above example. If a value is assigned to the expression result in the declaration, the parsing error occurs.

Example 12-7. declare staticVariable

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

Global and staticVariableReferences
In the first generation of Zend engine, PHP4 is driven.VariableThe static and global definitions of are implemented in the form of references. For example, a real global data imported using a global statement in a function domainVariableIn fact, a globalVariable. This may lead to unexpected behaviors, as demonstrated in the following example:

Code

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

Executing the preceding example will result in the following output:

NULLobject (stdClass) (0 ){}

Similar behavior applies to static statements. References are not stored statically:

Code

Function & get_instance_ref (){
Static $ obj;

Echo "Static object :";
Var_dump ($ obj );
If (! Isset ($ obj )){
// Assign a reference to a static objectVariable
$ Obj = & new stdclass;
}
$ Obj-> property ++;
Return $ obj;
}

Function & get_instance_noref (){
Static $ obj;

Echo "Static object :";
Var_dump ($ obj );
If (! Isset ($ obj )){
// Assign an object to a static objectVariable
$ Obj = new stdclass;
}
$ Obj-> property ++;
Return $ obj;
}

$ Obj1 = get_instance_ref ();
$ Still_obj1 = get_instance_ref ();
Echo "\ n ";
$ Obj2 = get_instance_noref ();
$ Still_obj2 = get_instance_noref ();
?>

Executing the preceding example will result in the following output:

Static object: NULLStatic object: object (stdClass) (1) {["property"] => int (1 )}


The previous example demonstrates how to assign a reference to a staticVariableThe value of the second call to the & get_instance_ref () function 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.