Php variable scope learning notes sharing _ PHP Tutorial

Source: Internet
Author: User
Php variable scope learning notes sharing. Variable scope is the scope of a variable that can be used between pages and functions, the following small series will introduce some learning notes about the use of php variables in the domain. the variable scope is a variable that can be used between pages and functions. Where can it be used, the following small series will introduce some learning notes about the use of the php variable domain to share with you.

The scope of variables in php is described in this way in the php Manual.

In a user-defined function, a local function range is introduced. By default, any variable used in a function is limited to a local function. For example:

The code is as follows:

$ 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 version of variable $ a and is not assigned a value within this range. You may notice that the global variables in PHP are a little different from those in C language. in C language, global variables automatically take effect in functions. unless they are overwritten by local variables, I will introduce it in detail below


In PHP, variables mainly include: Built-in super global variables, General variables, constants, global variables, static variables, and so on.

■ The built-in Super global variables 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 PHP scripts included in a page (including include and include_once, but it cannot be used in other pages.
■ The global variables declared in a script are visible throughout the script, but not inside the function. if the variables in the function are the same as the global variables, take the internal variables of the function as the standard.
■ When a variable used in a function is declared as a global variable, its name must be consistent with that of the global variable. in this case, we can use global variables outside the function, in this way, we can avoid the situation where the external variables are overwritten because the internal variables of the function are the same as the external global variables.
■ A variable created and declared as static within a function cannot be visible outside the function, but this value can be kept during multiple function executions, the most common case is the recursive execution of functions.
■ The variable created in the function is local to the function, and the variable does not exist when the function is terminated.
The complete list of Super global variables is as follows:

■. $ GOBALS all global variable arrays
■. $ _ SERVER environment variable array
■. $ _ POST the variable array passed to the script through the POST method
■. $ _ GET the variable array passed to the script through the GET method
■. $ _ COOKIE cookie variable array
■. $ _ FILES variable array related to file Upload
■. $ ENV environment variable array
■. $ _ REQUEST all input variable arrays by users include the input content included in the $ _ GET $ _ POST $ _ COOKIE
■. $ _ SESSION variable array


1. local variables

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

The code is as follows:

$ X = 4;

Function assignx (){

$ X = 0;

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

}

Assignx ();

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


The execution result is

$ Inside function is 0

$ Outside of function is 4

2. function parameters

Like other programming languages, any function that accepts parameters must declare these parameters in the function header. Although these parameters (value parameters) accept values outside the function, they cannot be accessed after exiting the function.

The code is as follows:

Function x10 ($ value ){
$ Value =

$ Value = $ value * 10

Return $ value;

}

Remember, although these function parameters can be accessed and output within the declared parameter function, the parameter is revoked when the function execution ends.

3. global variables

Global variables can be accessed anywhere in the program. However, to modify a global variable, you must explicitly declare it as a global variable in the function of this variable. If the keyword GLOBAL is added before the variable, it is the GLOBAL variable. If you place the GLOBA keyword before an existing variable, it tells PHP Yao to use a variable with the same name.


Use $ GLOBALS to replace global

The code is as follows:

$ 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 value variable content. $ GLOBALS exists globally because $ GLOBALS is a super global variable. The following example shows how to use a super global variable:
Example 12-3. Examples of hyperglobal variables and scopes

The code is as follows:

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 range and they do not require 'global' declarations. Superglobals was introduced in PHP 4.1.0.
Print $ _ POST ['name'];
}
?>


Use static variables

Another important feature of variable range is static variable ). Static variables only exist in local function domains, but their values are not lost when the program runs out of this scope. Take a look at the following example:
Example 12-4. example of static variables

The code is as follows:

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


This function is useless, because every call will set the value of $ a to 0 and output "0 ". Adding $ a ++ to the variable does not work, because $ a does not exist once you exit this function. To write a counting function that does not lose the current count value, you must define variable $ a as static:
Example 12-5. example of using static variables

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.
Static variables also provide 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. The simple function calculates 10 recursively and uses the static variable $ count to determine when to stop:
Example 12-6. static variables and recursive functions

The code is as follows:

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


Note: static variables can be declared according to the preceding example. If a value is assigned to the expression result in the declaration, the parsing error occurs.
Example 12-7. declare static variables

The code is as follows:

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

Be sure to ask meGlobal static variablesThere is no global variable in php.

Php is an interpreted language. although there is a static modifier, the meaning is completely different from that in. Net.
Even if you declare a variable in the class as static, this variable is only valid in the current page-level application domain.

2. understand the scope of variables.

Variables declared in vitro of the method cannot be accessed in the method body.
For example:

The code is as follows:

$ Url = "www. bKjia. c0m ";
Function _ DisplayUrl ()
{
Echo $ url;
}
Function DisplayUrl ()
{
Global $ url;
Echo $ url;
}
_ DisplayUrl ();
DisplayUrl ();
?>

$ Url = "www. bKjia. c0m ";
Function _ DisplayUrl ()
{
Echo $ url;
}
Function DisplayUrl ()
{
Global $ url;
Echo $ url;
}
_ DisplayUrl ();
DisplayUrl ();
?>

The _ DisplayUrl method does not display any results, because the variable $ url cannot be accessed in the method body _ DisplayUrl. you can add global before $ url, such as the DisplayUrl method.

Global variables defined in the method body can be accessed in the method body in vitro:

The code is as follows:


Function _ DisplayUrl ()
{
Global $ myName;
$ MyName = 'ibin ';
}

_ DisplayUrl ();
Echo $ myName; // output yibin
?>

...

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.