What is php variable scope?

怪我咯
Release: 2023-03-10 20:22:01
Original
1830 people have browsed it

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/-->
Copy after login


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/-->
Copy after login

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/-->
Copy after login

讲解:当函数被调用时,$a不能以参数的形式被传递。所以上面代码不能够正常运行。
变量范围
变量的范围即它定义的上下文背景(译者:说白了,也就是它的生效范围)。大部分的 PHP 变量只有一个单独的范围。这个单独的范围跨度同样包含了 include 和 require 引入的文件。范例:

代码如下:

Copy after login

这里变量 $a 将会在包含文件 b.inc 中生效。但是,在用户自定义函数中,一个局部函数范围将被引入。任何用于函数内部的变量按缺省情况将被限制在局部函数范围内。范例:

代码如下:

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->
Copy after login

这个脚本不会有任何输出,因为 echo 语句引用了一个局部版本的变量 $a,而且在这个范围内,它并没有被赋值。你可能注意到 PHP 的全局变量和 C 语言有一点点不同,在 C 语言中,全局变量在函数中自动生效,除非被局部变量覆盖。这可能引起一些问题,有些人可能漫不经心的改变一个全局变量。PHP 中全局变量在函数中使用时必须申明为全局。
The global keyword
首先,一个使用 global 的例子:
例子 12-1. 使用 global

代码如下:

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->
Copy after login

以上脚本的输出将是 "3"。在函数中申明了全局变量 $a 和 $b,任何变量的所有引用变量都会指向到全局变量。对于一个函数能够申明的全局变量的最大个数,PHP 没有限制。
在全局范围内访问变量的第二个办法,是用特殊的 PHP 自定义 $GLOBALS 数组。前面的例子可以写成:
例子 12-2. 使用 $GLOBALS 替代 global

代码如下:

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->
Copy after login

在 $GLOBALS 数组中,每一个变量为一个元素,键名对应变量名,值变量的内容。$GLOBALS 之所以在全局范围内存在,是因为 $GLOBALS 是一个超全局变量。以下范例显示了超全局变量的用处:
例子 12-3. 演示超全局变量和作用域的例子

代码如下:

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->
Copy after login

使用静态变量
变量范围的另一个重要特性是静态变量(static variable)。静态变量仅在局部函数域中存在,但当程序执行离开此作用域时,其值并不丢失。看看下面的例子:
例子 12-4. 演示需要静态变量的例子

代码如下:

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->
Copy after login

本函数没什么用处,因为每次调用时都会将 $a 的值设为 0 并输出 "0"。将变量加一的 $a++ 没有作用,因为一旦退出本函数则变量 $a 就不存在了。要写一个不会丢失本次计数值的计数函数,要将变量 $a 定义为静态的:
例子 12-5. 使用静态变量的例子

代码如下:

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->
Copy after login

现在,每次调用 Test() 函数都会输出 $a 的值并加一。
静态变量也提供了一种处理递归函数的方法。递归函数是一种调用自己的函数。写递归函数时要小心,因为可能会无穷递归下去。必须确保有充分的方法来中止递归。一下这个简单的函数递归计数到 10,使用静态变量 $count 来判断何时停止:
例子 12-6. 静态变量与递归函数

代码如下:

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->
Copy after login

注: 静态变量可以按照上面的例子声明。如果在声明中用表达式的结果对其赋值会导致解析错误。
例子 12-7. 声明静态变量

代码如下:

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->
Copy after login

全局和静态变量的引用
在 Zend 引擎 1 代,驱动了 PHP4,对于变量的 static 和 global 定义是以 references 的方式实现的。例如,在一个函数域内部用 global 语句导入的一个真正的全局变量实际上是建立了一个到全局变量的引用。这有可能导致预料之外的行为,如以下例子所演示的:

代码如下:

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->
Copy after login

执行以上例子会导致如下输出:

代码如下:

NULLobject(stdClass)(0) {}
Copy after login

类似的行为也适用于 static 语句。引用并不是静态地存储的:

代码如下:

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->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();
?>
Copy after login

执行以上例子会导致如下输出:

代码如下:

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

上例演示了当把一个引用赋值给一个静态变量时,第二次调用 &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!

Related labels:
source:php.cn
Statement of this Website
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 [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!