Note that unlike Java and C++, variables declared inside blocks such as loops or if's, will also be recognized and accessible outside of the block, so:
<?php
for($j=0; $j<3; $j++)
{
if($j == 1)
$a = 4;
}
echo $a;
?>
Would print 4.
变量的范围即它定义的上下文背景(也就是它的生效范围)。大部分的 PHP 变量只有一个单独的范围。这个单独的范围跨度同样包含了 include 和 require 引入的文件。例如:
<?php
$a = 1;
include 'b.inc';
?>
这里变量 $a 将会在包含文件 b.inc 中生效。但是,在用户自定义函数中,一个局部函数范围将被引入。任何用于函数内部的变量按缺省情况将被限制在局部函数范围内。例如:
<?php
$a = 1; /* global scope */
function Test()
{
echo $a; /* reference to local scope variable */
}
Test();
?>
这个脚本会生成未定义变量 E_WARNING
(PHP 8.0.0 之前是 E_NOTICE
)诊断提示。然而,如果 display_errors INI 设置为隐藏这类诊断提示,然后在任何情况下都不会有输出。这是因为
echo 语句引用了一个局部版本的变量 $a,而且在这个范围内,它并没有被赋值。你可能注意到
PHP 的全局变量和 C 语言有一点点不同,在 C
语言中,全局变量在函数中自动生效,除非被局部变量覆盖。这可能引起一些问题,有些人可能不小心就改变了一个全局变量。PHP
中全局变量在函数中使用时必须声明为 global。
首先,一个使用 global
的例子:
示例 #1 使用 global
<?php
$a = 1;
$b = 2;
function Sum()
{
global $a, $b;
$b = $a + $b;
}
Sum();
echo $b;
?>
以上脚本的输出将是“3”。在函数中声明了全局变量 $a 和 $b 之后,对任一变量的所有引用都会指向其全局版本。对于一个函数能够声明的全局变量的最大个数,PHP 没有限制。
在全局范围内访问变量的第二个办法,是用特殊的 PHP 自定义 $GLOBALS 数组。前面的例子可以写成:
示例 #2 使用 $GLOBALS 替代 global
<?php
$a = 1;
$b = 2;
function Sum()
{
$GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
}
Sum();
echo $b;
?>
$GLOBALS 是一个关联数组,每一个变量为一个元素,键名对应变量名,值对应变量的内容。$GLOBALS 之所以在全局范围内存在,是因为 $GLOBALS 是一个超全局变量。以下范例显示了超全局变量的用处:
示例 #3 演示超全局变量和作用域的例子
<?php
function test_superglobal()
{
echo $_POST['name'];
}
?>
变量范围的另一个重要特性是静态变量(static variable)。静态变量仅在局部函数域中存在,但当程序执行离开此作用域时,其值并不丢失。看看下面的例子:
示例 #4 演示需要静态变量的例子
<?php
function Test()
{
$a = 0;
echo $a;
$a++;
}
?>
本函数没什么用处,因为每次调用时都会将
$a 的值设为 0
并输出
0
。将变量加一的 $a++
没有作用,因为一旦退出本函数则变量
$a 就不存在了。要写一个不会丢失本次计数值的计数函数,要将变量
$a 定义为静态的:
示例 #5 使用静态变量的例子
<?php
function test()
{
static $a = 0;
echo $a;
$a++;
}
?>
现在,变量 $a 仅在第一次调用 test() 函数时被初始化,之后每次调用 test() 函数都会输出 $a 的值并加一。
静态变量也提供了一种处理递归函数的方法。递归函数是一种调用自己的函数。写递归函数时要小心,因为可能会无穷递归下去。必须确保有充分的方法来中止递归。以下这个简单的函数递归计数到 10,使用静态变量 $count 来判断何时停止:
示例 #6 静态变量与递归函数
<?php
function test()
{
static $count = 0;
$count++;
echo $count;
if ($count < 10) {
test();
}
$count--;
}
?>
常量表达式的结果可以赋值给静态变量,但是动态表达式(比如函数调用)会导致解析错误。
示例 #7 声明静态变量
<?php
function foo(){
static $int = 0; // 正确
static $int = 1+2; // 正确
static $int = sqrt(121); // 错误(因为它是函数)
$int++;
echo $int;
}
?>
从 PHP 8.1.0 开始,当继承(不是覆盖)使用有静态变量的方法时,继承的方法将会跟父级方法共享静态变量。这意味着方法中的静态变量现在跟静态属性有相同的行为。
示例 #8 在继承方法中使用静态变量
<?php
class Foo {
public static function counter() {
static $counter = 0;
$counter++;
return $counter;
}
}
class Bar extends Foo {}
var_dump(Foo::counter()); // int(1)
var_dump(Foo::counter()); // int(2)
var_dump(Bar::counter()); // int(3),PHP 8.1.0 之前 int(1)
var_dump(Bar::counter()); // int(4),PHP 8.1.0 之前 int(2)
?>
注意:
静态声明在编译时解析。
对于变量的
static 和
global
定义是以引用的方式实现的。例如,在一个函数域内部用
global
语句导入的一个真正的全局变量实际上是建立了一个到全局变量的引用。这有可能导致预料之外的行为,如以下例子所演示的:
<?php
function test_global_ref() {
global $obj;
$new = new stdClass;
$obj = &$new;
}
function test_global_noref() {
global $obj;
$new = new stdClass;
$obj = $new;
}
test_global_ref();
var_dump($obj);
test_global_noref();
var_dump($obj);
?>
以上示例会输出:
NULL object(stdClass)#1 (0) { }
类似的行为也适用于
static
语句。引用并不是静态地存储的:
<?php
function &get_instance_ref() {
static $obj;
echo 'Static object: ';
var_dump($obj);
if (!isset($obj)) {
$new = new stdClass;
// 将一个引用赋值给静态变量
$obj = &$new;
}
if (!isset($obj->property)) {
$obj->property = 1;
} else {
$obj->property++;
}
return $obj;
}
function &get_instance_noref() {
static $obj;
echo 'Static object: ';
var_dump($obj);
if (!isset($obj)) {
$new = new stdClass;
// 将一个对象赋值给静态变量
$obj = $new;
}
if (!isset($obj->property)) {
$obj->property = 1;
} else {
$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: NULL Static object: NULL Static object: NULL Static object: object(stdClass)#3 (1) { ["property"]=> int(1) }
上例演示了当把一个引用赋值给一个静态变量时,第二次调用
&get_instance_ref()
函数时其值并没有被记住。
Note that unlike Java and C++, variables declared inside blocks such as loops or if's, will also be recognized and accessible outside of the block, so:
<?php
for($j=0; $j<3; $j++)
{
if($j == 1)
$a = 4;
}
echo $a;
?>
Would print 4.
Some interesting behavior (tested with PHP5), using the static-scope-keyword inside of class-methods.
<?php
class sample_class
{
public function func_having_static_var($x = NULL)
{
static $var = 0;
if ($x === NULL)
{ return $var; }
$var = $x;
}
}
$a = new sample_class();
$b = new sample_class();
echo $a->func_having_static_var()."\n";
echo $b->func_having_static_var()."\n";
// this will output (as expected):
// 0
// 0
$a->func_having_static_var(3);
echo $a->func_having_static_var()."\n";
echo $b->func_having_static_var()."\n";
// this will output:
// 3
// 3
// maybe you expected:
// 3
// 0
?>
One could expect "3 0" to be outputted, as you might think that $a->func_having_static_var(3); only alters the value of the static $var of the function "in" $a - but as the name says, these are class-methods. Having an object is just a collection of properties, the functions remain at the class. So if you declare a variable as static inside a function, it's static for the whole class and all of its instances, not for each object.
Maybe it's senseless to post that.. cause if you want to have the behaviour that I expected, you can simply use a variable of the object itself:
<?php
class sample_class
{ protected $var = 0;
function func($x = NULL)
{ $this->var = $x; }
} ?>
I believe that all normal-thinking people would never even try to make this work with the static-keyword, for those who try (like me), this note maybe helpfull.
Static variables do not hold through inheritance. Let class A have a function Z with a static variable. Let class B extend class A in which function Z is not overwritten. Two static variables will be created, one for class A and one for class B.
Look at this example:
<?php
class A {
function Z() {
static $count = 0;
printf("%s: %d\n", get_class($this), ++$count);
}
}
class B extends A {}
$a = new A();
$b = new B();
$a->Z();
$a->Z();
$b->Z();
$a->Z();
?>
This code returns:
A: 1
A: 2
B: 1
A: 3
As you can see, class A and B are using different static variables even though the same function was being used.
Took me longer than I expected to figure this out, and thought others might find it useful.
I created a function (safeinclude), which I use to include files; it does processing before the file is actually included (determine full path, check it exists, etc).
Problem: Because the include was occurring inside the function, all of the variables inside the included file were inheriting the variable scope of the function; since the included files may or may not require global variables that are declared else where, it creates a problem.
Most places (including here) seem to address this issue by something such as:
<?php
//declare this before include
global $myVar;
//or declare this inside the include file
$nowglobal = $GLOBALS['myVar'];
?>
But, to make this work in this situation (where a standard PHP file is included within a function, being called from another PHP script; where it is important to have access to whatever global variables there may be)... it is not practical to employ the above method for EVERY variable in every PHP file being included by 'safeinclude', nor is it practical to staticly name every possible variable in the "global $this" approach. (namely because the code is modulized, and 'safeinclude' is meant to be generic)
My solution: Thus, to make all my global variables available to the files included with my safeinclude function, I had to add the following code to my safeinclude function (before variables are used or file is included)
<?php
foreach ($GLOBALS as $key => $val) { global $$key; }
?>
Thus, complete code looks something like the following (very basic model):
<?php
function safeinclude($filename)
{
//This line takes all the global variables, and sets their scope within the function:
foreach ($GLOBALS as $key => $val) { global $$key; }
/* Pre-Processing here: validate filename input, determine full path
of file, check that file exists, etc. This is obviously not
necessary, but steps I found useful. */
if ($exists==true) { include("$file"); }
return $exists;
}
?>
In the above, 'exists' & 'file' are determined in the pre-processing. File is the full server path to the file, and exists is set to true if the file exists. This basic model can be expanded of course. In my own, I added additional optional parameters so that I can call safeinclude to see if a file exists without actually including it (to take advantage of my path/etc preprocessing, verses just calling the file exists function).
Pretty simple approach that I could not find anywhere online; only other approach I could find was using PHP's eval().
About more complex situation using global variables..
Let's say we have two files:
a.php
<?php
function a() {
include("b.php");
}
a();
?>
b.php
<?php
$b = "something";
function b() {
global $b;
$b = "something new";
}
b();
echo $b;
?>
You could expect that this script will return "something new" but no, it will return "something". To make it working properly, you must add global keyword in $b definition, in above example it will be:
global $b;
$b = "something";
In fact all variables represent pointers that hold address of memory area with data that was assigned to this variable. When you assign some variable value by reference you in fact write address of source variable to recepient variable. Same happens when you declare some variable as global in function, it receives same address as global variable outside of function. If you consider forementioned explanation it's obvious that mixing usage of same variable declared with keyword global and via superglobal array at the same time is very bad idea. In some cases they can point to different memory areas, giving you headache. Consider code below:
<?php
error_reporting(E_ALL);
$GLOB = 0;
function test_references() {
global $GLOB; // get reference to global variable using keyword global, at this point local variable $GLOB points to same address as global variable $GLOB
$test = 1; // declare some local var
$GLOBALS['GLOB'] = &$test; // make global variable reference to this local variable using superglobal array, at this point global variable $GLOB points to new memory address, same as local variable $test
$GLOB = 2; // set new value to global variable via earlier set local representation, write to old address
echo "Value of global variable (via local representation set by keyword global): $GLOB <hr>";
// check global variable via local representation => 2 (OK, got value that was just written to it, cause old address was used to get value)
echo "Value of global variable (via superglobal array GLOBALS): $GLOBALS[GLOB] <hr>";
// check global variable using superglobal array => 1 (got value of local variable $test, new address was used)
echo "Value ol local variable \$test: $test <hr>";
// check local variable that was linked with global using superglobal array => 1 (its value was not affected)
global $GLOB; // update reference to global variable using keyword global, at this point we update address that held in local variable $GLOB and it gets same address as local variable $test
echo "Value of global variable (via updated local representation set by keyword global): $GLOB <hr>";
// check global variable via local representation => 1 (also value of local variable $test, new address was used)
}
test_references();
echo "Value of global variable outside of function: $GLOB <hr>";
// check global variable outside function => 1 (equal to value of local variable $test from function, global variable also points to new address)
?>
If you have a static variable in a method of a class, all DIRECT instances of that class share that one static variable.
However if you create a derived class, all DIRECT instances of that derived class will share one, but DISTINCT, copy of that static variable in method.
To put it the other way around, a static variable in a method is bound to a class (not to instance). Each subclass has own copy of that variable, to be shared among its instances.
To put it yet another way around, when you create a derived class, it 'seems to' create a copy of methods from the base class, and thusly create copy of the static variables in those methods.
Tested with PHP 7.0.16.
<?php
require 'libs.php';
require 'setup.php';
class Base {
function test($delta = 0) {
static $v = 0;
$v += $delta;
return $v;
}
}
class Derived extends Base {}
$base1 = new Base();
$base2 = new Base();
$derived1 = new Derived();
$derived2 = new Derived();
$base1->test(3);
$base2->test(4);
$derived1->test(5);
$derived2->test(6);
var_dump([ $base1->test(), $base2->test(), $derived1->test(), $derived2->test() ]);
# => array(4) { [0]=> int(7) [1]=> int(7) [2]=> int(11) [3]=> int(11) }
# $base1 and $base2 share one copy of static variable $v
# derived1 and $derived2 share another copy of static variable $v
If you use __autoload function to load classes' definitons, beware that "static local variables are resolved at compile time" (whatever it really means) and the order in which autoloads occur may impact the semantic.
For example if you have:
<?php
class Singleton{
static public function get_instance(){
static $instance = null;
if($instance === null){
$instance = new static();
}
return $instance;
}
}
?>
and two separate files A.php and B.php:
class A extends Singleton{}
class B extends A{}
then depending on the order in which you access those two classes, and consequently, the order in which __autoload includes them, you can get strange results of calling B::get_instance() and A::get_instance().
It seems that static local variables are alocated in as many copies as there are classes that inherit a method at the time of inclusion of parsing Singleton.
Use the superglobal array $GLOBALS is faster than the global keyword. See:
<?php
//Using the keyword global
$a=1;
$b=2;
function sum() {
global $a, $b;
$a += $b;
}
$t = microtime(true);
for($i=0; $i<1000; $i++) {
sum();
}
echo microtime(true)-$t;
echo " -- ".$a."<br>";
//Using the superglobal array
$a=1;
$b=2;
function sum2() {
$GLOBALS['a'] += $GLOBALS['b'];
}
$t = microtime(true);
for($i=0; $i<1000; $i++) {
sum2();
}
echo microtime(true)-$t;
echo " -- ".$a."<br>";
?>
To be vigilant, unlike Java or C++, variables declared inside blocks such as loops (for, while,...) or if's, will also be recognized and accessible outside of the block, the only valid block is the BLOCK function so:
<?php
for($j=0; $j<5; $j++)
{
if($j == 1){
$a = 6;
}
}
echo $a;
?>
Would print 6.
writing : global $var; is exactely the samething that writing : $var =& $GLOBALS['var'];
It creates a reference on $GLOBALS['var'];
<?php
$var =1;
function teste_global(){
global $var;
for ($var=0; $var<5; $var++){
}
}
teste_global();
var_dump($var);// return : int(5).
?>
It should be noted that a static variable inside a method is static across all instances of that class, i.e., all objects of that class share the same static variable. For example the code:
<?php
class test {
function z() {
static $n = 0;
$n++;
return $n;
}
}
$a =& new test();
$b =& new test();
print $a->z(); // prints 1, as it should
print $b->z(); // prints 2 because $a and $b have the same $n
?>
somewhat unexpectedly prints:
1
2
Beware of using $this in anonymous functions assigned to a static variable.
<?php
class Foo {
public function bar() {
static $anonymous = null;
if ($anonymous === null) {
// Expression is not allowed as static initializer workaround
$anonymous = function () {
return $this;
};
}
return $anonymous();
}
}
$a = new Foo();
$b = new Foo();
var_dump($a->bar() === $a); // True
var_dump($b->bar() === $a); // Also true
?>
In a static anonymous function, $this will be the value of whatever object instance that method was called on first.
To get the behaviour you're probably expecting, you need to pass the $this context into the function.
<?php
class Foo {
public function bar() {
static $anonymous = null;
if ($anonymous === null) {
// Expression is not allowed as static initializer workaround
$anonymous = function (self $thisObj) {
return $thisObj;
};
}
return $anonymous($this);
}
}
$a = new Foo();
$b = new Foo();
var_dump($a->bar() === $a); // True
var_dump($b->bar() === $a); // False
?>