PHP Variable Scope Learning notes sharing

Source: Internet
Author: User
Tags parse error php and php script valid variable scope

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

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

The code is as follows Copy Code

<?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 C, the global variable automatically takes effect in the function, unless it is covered by a local variable, and the top is open, let me explain


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 array of all global variables
.$_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 an array of environment variables
.$_request all user-entered variable arrays include input from $_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 copied outside the function, it is said to be a completely different variable (that is, different from the variable contained in the function). Note that when you exit the function that declares the 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 <br/>", $x);

}

Assignx ();

printf ("$x outside of function is%d <br/>", $x);


Execution results are

$ inside function is 0

$ Outside of function is 4

2, function parameters

PHP and other programming languages, any function that accepts parameters must declare these parameters in the first part of the letter. 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 the function arguments can be accessed and output within the function that declares the parameter, the arguments are undone when the function is finished.

3. Global variables

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


Replace Global with $GLOBALS

The code is as follows Copy Code

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

The code is as follows Copy Code

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

The code is as follows Copy Code

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

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

The code is as follows Copy Code

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

The code is as follows Copy Code

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

Pay attention to a friend ask me global static variable , there is no global variable in PHP this is said to live

PHP is an interpreted language, although it has a static modifier, but the meaning is the same as the. NET is completely different.
This variable is only valid in the current page-level application domain, even if one of the variables in the class is declared static.

2. Understand the scope of variables.

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

  code is as follows copy code

 

<?php  
  $url = "Www.111cn.net";  
  function _displayurl ()   
  {  
      echo $url;  
 }  
  Fun Ction Displayurl ()   
  {  
    global $url;  
 & nbsp;  echo $url;  
 }  
  _displayurl ();  
  Displayur L ();  

<?php
  $url = "www.111cn.net";
  function _displayurl () br>   {
      echo $url;
 }
  function Displayurl ()
  {
    Global $url;
    echo $url;
 }
  _displayurl ();
  Displayurl ();
?

The _displayurl method does not display any results because the variable $url is inaccessible in the method body _displayurl, plus global before $url, such as the Displayurl method.

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

The code is as follows Copy Code


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

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