search
HomeBackend DevelopmentPHP TutorialPHP variable scope study notes sharing_PHP tutorial

PHP variable scope study notes sharing_PHP tutorial

Jul 13, 2016 am 10:50 AM
phpandScopeusefunctionsharevariableexiststudynotespage

Variable scope refers to whether a variable can be used with each other between pages and functions. What is its scope of action? Let me introduce some study notes of PHP variable usage scope to share with you.

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

In user-defined functions, a local function scope will be introduced. Any variables used inside a function will be restricted to the local function scope by default. For example:

The code is as follows Copy code
 代码如下 复制代码

$a = 1; /* global scope */

function Test()
{
   echo $a; /* reference to local scope variable */
}

Test();
?>

$a = 1; /* global scope */

function Test()
{

echo $a; /* reference to local scope variable */

}

Test();
?>


This script will produce no output because the echo statement refers to a local version of the variable $a, and it is not assigned a value within this scope. You may have noticed that PHP’s global variables are a little different from C language. In C language, global variables automatically take effect in functions unless overridden by local variables. Let’s start with the above. Let me introduce it in detail below

Variables in PHP mainly include: built-in super global variables, general variables, constants, global variables, static variables, etc.

■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, its value will also change when used in other PHP pages.
■Constants once declared will be globally visible, that is, they can be used inside and outside functions, but this is only limited to one page (including PHP scripts we include through include and include_once), but in other pages Can no longer be used.
■Global variables declared in a script are visible throughout the script, but not inside the function. If the variable inside the function has the same name as the global variable, the variable inside the function shall prevail.
■When the variables used inside the function are declared as global variables, their names must be consistent with the names of the global variables. In this case, we can use the global variables outside the function in the function, so as to avoid the previous problem. The variable inside the function has the same name as the external global variable and overrides the external variable.
■Variables created and declared as static inside a function cannot be visible outside the function, but the value can be maintained during multiple executions of the function. The most common situation is during the recursive execution of the function.
■Variables created within a function are local to the function and cease to exist when the function terminates.
The complete list of super global variables is as follows:

■.$GOBALS Array of all global variables
■.$_SERVER server environment variable array

■.$_POST Array of variables passed to this script via the POST method

■.$_GET Array of variables passed to this script via the GET method

■.$_COOKIE cookie variable array
 代码如下 复制代码

$x=4;

function assignx(){

$x=0;

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

}

assignx();

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

 
执行结果为

$ inside function is 0

$ outside of function is 4

■.$_FILES Array of variables related to file upload ■.$ENV environment variable array ■.$_REQUEST All user-input variable arrays include the input content contained in $_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 within the function. If copied outside a function, it is considered a completely different variable (that is, different from the one contained in the function). Note that when you exit the function in which the variable was declared, the variable and its corresponding value are destroyed.
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); The execution result is $ inside function is 0 $ outside of function is 4

2. Function parameters

PHP, like other programming languages, any function that accepts parameters must declare these parameters in the function header. Although these parameters (value parameters) accept values ​​from 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;

}

function x10($value){

$value=

$value=$value*10

return $value;

}

Remember that although these function parameters can be accessed and manipulated within the function in which they are declared, the parameters will be destroyed when the function execution ends.
 代码如下 复制代码

 

$a = 1;
$b = 2;
function Sum()
{
   $GLOBALS["b"] = $GLOBALS["a"] + $GLOBALS["b"];
}
Sum();
echo $b;
?>

3. Global variables

Global variables can be accessed anywhere in the program. However, in order to modify a global variable, it must be explicitly declared as a global variable in the function that modifies the variable. As long as the keyword GLOBAL is added in front of the variable, it is a global variable. If you put the GLOBA keyword in front of an existing variable, it tells PHP to use the variable with the same name.

 代码如下 复制代码

 

function test_global()
{
   // 大多数的预定义变量并不 "super",它们需要用 'global' 关键字来使它们在函数的本地区域中有效。
   global $HTTP_POST_VARS;
   print $HTTP_POST_VARS['name'];
   // Superglobals 在任何范围内都有效,它们并不需要 'global' 声明。Superglobals 是在 PHP 4.1.0 引入的。
   print $_POST['name'];
}
?>

Use $GLOBALS instead of global

The code is as follows Copy code


$a = 1;

 代码如下 复制代码

 

function Test ()
{
   $a = 0;
   echo $a;
   $a++;
}
?>

$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 value variable content. $GLOBALS exists in the global scope because $GLOBALS is a superglobal variable. The following example shows the use of superglobal variables: Example 12-3. Example demonstrating superglobal variables and scope
The code is as follows Copy code
function test_global() { // Most predefined variables are not "super", they require the 'global' keyword to make them available in the local scope 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 were introduced in PHP 4.1.0. Print $_POST['name']; } ?>
Use static variables Another important feature of variable scope is static variables. Static variables only exist in the local function scope, but their values ​​are not lost when program execution leaves this scope. Take a look at the example below: Example 12-4. Demonstrates the need for static variables
The code is as follows Copy code
function Test () { $a = 0; echo $a; $a++; } ?>


This function is not very useful because it sets the value of $a to 0 and prints "0" every time it is called. $a++, which increments a variable by one, has no effect because the variable $a no longer exists once this function exits. To write a counting function that does not lose the current count value, define the variable $a as static:
Example 12-5. Example of using static variables

function Test()
{
static $a = 0;
echo $a;
$a++;
}
?>


Now, each call to the Test() function will output the value of $a and increment it by 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 they may recurse indefinitely. You must ensure that there are adequate ways to terminate recursion. Consider this simple function that recursively counts to 10, using the 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    Test ();
   }
   $count--;
}
?>


function Test()

{
 代码如下 复制代码

 

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

static $count = 0;

$count++; echo $count; if ($count Test ();

}
$count--;

}

?>


Note: Static variables can be declared as in the above example. Assigning it with the result of an expression in a declaration will result in a parsing error.

Example 12-7. Declare static variables
 代码如下 复制代码

 

  $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 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 about global static variables. There is no such thing as global variables in php php is an interpreted language. Although it has the static modifier, its meaning is completely different from that in .Net. Even if a variable in the class is declared static, this variable is only valid in the current page-level application domain. 2. Understand variable scope. Variables declared outside the method cannot be accessed within the method body. Such as:
The code is as follows Copy code
$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 will not display any results because the variable $url is inaccessible in the method body _DisplayUrl. Just add global before $url, such as the DisplayUrl method.

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

The code is as follows
 代码如下 复制代码


  function _DisplayUrl()  
  {  
      global $myName;  
      $myName='yibin';  
  }  
    
  _DisplayUrl();  
  echo $myName;  //output yibin  
?> 

Copy code

function _DisplayUrl()

global $myName;
        $myName='yibin';                                                  } 
         
_DisplayUrl();
echo $myName; //output yibin
?>

http://www.bkjia.com/PHPjc/632648.htmlwww.bkjia.comtrue
http: //www.bkjia.com/PHPjc/632648.html
TechArticle
Variable scope is whether a variable can be used with each other between the page and the function. What is its scope? The editor below will introduce to you some study notes on the use of php variables...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools