PHP的static变量初始化问题

本文详细解析PHP中静态变量的定义、赋值规则及实例应用,包括类中静态成员变量的声明与作用域,以及在函数内如何正确使用静态变量,通过实例演示静态变量只被赋值一次但后续操作如同普通变量的特性。

知识点:

一、static变量只能使用使用基本类型的字面值赋值,通过表达式、对象或函数返回值赋值的操作都是不允许的

二、静态变量声明是在编译时解析的

下面看几个例子。

1.类中的static成员变量

class Test { public static $t = array('asdf', 1234); public function __construct() { echo "ok/n"; } function hi() { echo "hello/n"; } }

class TestWithImproperStatement { // public static $str = new Test(); // error, syntax error, unexpected 'new' function hi() { echo "hello"; } }

上面两段代码均含有static成员变量,但是第二个类如果打开注释部分,就会出现编译错误,因为 new Test(); 不是基本类型字面值。

2.函数中的成员变量

/** * Note: Static declarations are resolved in compile-time. * * @return Test */ function mytest1() { // static $test = new Test(); // Parse error: syntax error, unexpected T_NEW // static $int = 1+2; // wrong (as it is an expression) // static $int = sqrt(121); // wrong (as it is an expression too) return $test; } /** * @return Test */ function mytest2() { static $test = null; if (!$test) { $test = new Test(); } echo 'mytest2 '; return $test; } /** * @return Test */ function mytest3() { static $test = null; $test = new Test(); echo 'mytest3 '; return $test; }

mytest1 注释掉的代码就是编译出错的部分,错误原因与上面例子描述相同,这里我们着重看下 mytest2 和 mytest3,运行下面代码:

mytest2()->hi(); mytest2()->hi(); mytest2()->hi(); mytest3()->hi(); mytest3()->hi(); mytest3()->hi(); /* 代码输出结果 ok mytest2 hello mytest2 hello mytest2 hello ok mytest3 hello ok mytest3 hello ok mytest3 hello */

从运行结果中可以看出,static 变量虽然只被赋值一次,但这只局限于 static $var = xxx; 这一行代码,对于后期的赋值操作跟普通变量赋值完全一样,如 mytest3 中 $test = new Test();。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值