只是好奇。
如果我在 __construct
类中分配 self::$session = $reg->get('session');
,该变量可以用作类吗' 属性就像 $this->session = $reg->get('session');
?
我不知道如何测试这个。我测试这一点的唯一方法是通过更改所有框架来毁掉我的整个框架。
最佳答案
刚刚尝试了一下 PHP shell (php -a
) 上的可能性。
php > class a { public $b; function __construct () { self::$b = 10; } }
php > $o = new a;
PHP Fatal error: Access to undeclared static property: a::$b in php shell code on line 1
php > class a { public static $b; function __construct () { $this->b = 10; } }
php > $o = new a;
php > print $o->b;
10
php > print a::$b;
php > // outputs nothing (is still NULL)
php > class a { public static $b; function __construct () { self::$b = 10; } }
php > $o = new a;
php > print $o->b;
PHP Notice: Undefined property: a::$b in php shell code on line 1
php > // doesn't print a value (basically NULL)
我们发现了什么
- 您无法像静态属性一样分配非静态属性(使用
self::...
)。 - 您可以像分配非静态属性一样分配静态属性。但它创建了一个新的隐式非静态公共(public)属性,而不是更改静态属性的值。
- 您无法像访问非静态属性一样访问静态属性。
结论
不可以,您无法在静态和非静态访问和写入之间切换。
关于php - 使用范围解析运算符(::) 分配变量与 $this->variable 相同吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16881086/