Home > Article > Backend Development > What is php variable scope?
This article is a detailed analysis and introduction to the scope of PHP variables. Friends who need it can refer to it
Every variable in PHP has a scope for it, which means that it can be A field in which a variable (and thus its value) is accessed. For starters, the scope of variables is the page they reside on. Therefore, if you define $var, the rest of the page can access $var, but other pages generally cannot access it (unless special variables are used).
Because included files work as if they were part of the original (included) script, variables defined before the include() line are available to the included file. Additionally, variables defined within the include file are available to the parent (include) script after the include() line.
All of this will become less obvious when using your own defined functions. These functions have their own scope, which means that variables used within a function cannot be used outside it, and variables defined outside a function cannot be used inside it. For this reason, variables inside a function can have the same name as variables outside it, but they will still be completely different variables with different values. This is a confusing concept for most junior programmers.
To change the scope of variables within a function, you can use the global statement.
The code is as follows:
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--><?php 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 means that the variable $var already has a value of 20, and if this value is changed inside the function, the value of $var outside will also change.
Another way to avoid variable scope is to use super global variables : $_GET, $_POST, $_REQUEST, etc. These variables are automatically accessible within your function (thus, they are superglobal variables). You can also add elements to the $GLOBALS array so that they can be used within functions.
In other words, it is best not to use global variables within functions. When designing functions, you should make them accept every value as a parameter as needed and return any value as needed. Relying on global variables within functions would make them more context-dependent and therefore less useful.
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 PHP scripts included in a page (including the PHP scripts we include through include and include_once), but It cannot be used in other pages.
•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 a variable used inside a function is declared as a global variable, its name must be consistent with the name of the global variable. In this case, we can use the global variable outside the function in the function , this can avoid the previous situation where the external variable is overwritten because the variable inside the function has the same name as the external global 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 inside 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 Array of server environment variables
•. $_POST Variable array passed to the script through the POST method
•.$_GET Variable array passed to the script through the GET method
•.$_COOKIE cookie variable array
•.$_FILES Related to file upload Variable array
•.$_ENV Environment variable array
•.$_REQUEST Variable array entered by all users including input content contained in $_GET $_POST $_COOKIE
•.$_SESSION Session variable array
Example explanation:
The code is as follows:
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--><?php $a = 4; function sendValue($x) { echo $x; } sendValue($a); ?>
Explanation: $a is defined outside the function, and the function defines parameters. When the function is called, $ a will be passed as a parameter. So the above code can run normally.
code show as below:
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--><?php $a = 4; function sendValue() { echo $a; } sendValue(); ?>
讲解:当函数被调用时,$a不能以参数的形式被传递。所以上面代码不能够正常运行。
变量范围
变量的范围即它定义的上下文背景(译者:说白了,也就是它的生效范围)。大部分的 PHP 变量只有一个单独的范围。这个单独的范围跨度同样包含了 include 和 require 引入的文件。范例:
代码如下:
<?php $a = 1; include "b.inc"; ?>
这里变量 $a 将会在包含文件 b.inc 中生效。但是,在用户自定义函数中,一个局部函数范围将被引入。任何用于函数内部的变量按缺省情况将被限制在局部函数范围内。范例:
代码如下:
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--><?php $a = 1; /* global scope */ function Test() { echo $a; /* reference to local scope variable */ } Test(); ?>
这个脚本不会有任何输出,因为 echo 语句引用了一个局部版本的变量 $a,而且在这个范围内,它并没有被赋值。你可能注意到 PHP 的全局变量和 C 语言有一点点不同,在 C 语言中,全局变量在函数中自动生效,除非被局部变量覆盖。这可能引起一些问题,有些人可能漫不经心的改变一个全局变量。PHP 中全局变量在函数中使用时必须申明为全局。
The global keyword
首先,一个使用 global 的例子:
例子 12-1. 使用 global
代码如下:
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--><?php $a = 1; $b = 2; function Sum() { global $a, $b; $b = $a + $b; } Sum(); echo $b; ?>
以上脚本的输出将是 "3"。在函数中申明了全局变量 $a 和 $b,任何变量的所有引用变量都会指向到全局变量。对于一个函数能够申明的全局变量的最大个数,PHP 没有限制。
在全局范围内访问变量的第二个办法,是用特殊的 PHP 自定义 $GLOBALS 数组。前面的例子可以写成:
例子 12-2. 使用 $GLOBALS 替代 global
代码如下:
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--><?php $a = 1; $b = 2; function Sum() { $GLOBALS["b"] = $GLOBALS["a"] + $GLOBALS["b"]; } Sum(); echo $b; ?>
在 $GLOBALS 数组中,每一个变量为一个元素,键名对应变量名,值变量的内容。$GLOBALS 之所以在全局范围内存在,是因为 $GLOBALS 是一个超全局变量。以下范例显示了超全局变量的用处:
例子 12-3. 演示超全局变量和作用域的例子
代码如下:
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--><?php function test_global() { // 大多数的 预定义变量 并不 "super",它们需要用 'global' 关键字来使它们在函数的本地区域中有效。 global $HTTP_POST_VARS; print $HTTP_POST_VARS['name']; // Superglobals 在任何范围内都有效,它们并不需要 'global' 声明。Superglobals 是在 PHP 4.1.0 引入的。 print $_POST['name']; } ?>
使用静态变量
变量范围的另一个重要特性是静态变量(static variable)。静态变量仅在局部函数域中存在,但当程序执行离开此作用域时,其值并不丢失。看看下面的例子:
例子 12-4. 演示需要静态变量的例子
代码如下:
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--><?php function Test () { $a = 0; echo $a; $a++; } ?>
本函数没什么用处,因为每次调用时都会将 $a 的值设为 0 并输出 "0"。将变量加一的 $a++ 没有作用,因为一旦退出本函数则变量 $a 就不存在了。要写一个不会丢失本次计数值的计数函数,要将变量 $a 定义为静态的:
例子 12-5. 使用静态变量的例子
代码如下:
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--><?php function Test() { static $a = 0; echo $a; $a++; } ?>
现在,每次调用 Test() 函数都会输出 $a 的值并加一。
静态变量也提供了一种处理递归函数的方法。递归函数是一种调用自己的函数。写递归函数时要小心,因为可能会无穷递归下去。必须确保有充分的方法来中止递归。一下这个简单的函数递归计数到 10,使用静态变量 $count 来判断何时停止:
例子 12-6. 静态变量与递归函数
代码如下:
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--><?php function Test() { static $count = 0; $count++; echo $count; if ($count < 10) { Test (); } $count--; } ?>
注: 静态变量可以按照上面的例子声明。如果在声明中用表达式的结果对其赋值会导致解析错误。
例子 12-7. 声明静态变量
代码如下:
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--><?php 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; } ?>
全局和静态变量的引用
在 Zend 引擎 1 代,驱动了 PHP4,对于变量的 static 和 global 定义是以 references 的方式实现的。例如,在一个函数域内部用 global 语句导入的一个真正的全局变量实际上是建立了一个到全局变量的引用。这有可能导致预料之外的行为,如以下例子所演示的:
代码如下:
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--><?php 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); ?>
执行以上例子会导致如下输出:
代码如下:
NULLobject(stdClass)(0) {}
类似的行为也适用于 static 语句。引用并不是静态地存储的:
代码如下:
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--><?php function &get_instance_ref() { static $obj; echo "Static object: "; var_dump($obj); if (!isset($obj)) { // 将一个引用赋值给静态变量 $obj = &new stdclass; } $obj->property++; return $obj; } function &get_instance_noref() { static $obj; echo "Static object: "; var_dump($obj); if (!isset($obj)) { // 将一个对象赋值给静态变量 $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(); ?>
执行以上例子会导致如下输出:
代码如下:
Static object: NULLStatic object: NULLStatic object: NULLStatic object: object(stdClass)(1) { ["property"]=> int(1)}
上例演示了当把一个引用赋值给一个静态变量时,第二次调用 &get_instance_ref() 函数时其值并没有被记住。
The above is the detailed content of What is php variable scope?. For more information, please follow other related articles on the PHP Chinese website!