是否使用与$ this-> variable相同的Scope Resolution Operator(::)分配变量?

use*_*495 2 php variables class

只是好奇.

如果我self::$session = $reg->get('session');在一个__construct类中赋值,该变量是否可以用作类的属性 $this->session = $reg->get('session');

我不知道如何测试这个.我可以测试这个的唯一方法是通过更改它们来使我的整个框架处于毁灭状态.

bwo*_*ebi 5

只是尝试了一下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)
Run Code Online (Sandbox Code Playgroud)

我们发现了什么

  • 您不能像静态属性(with self::...)一样分配非静态属性.
  • 您可以指定静态属性,如非静态属性.但它创建了一个新的隐式非静态公共属性,而不是更改静态属性的值.
  • 您无法访问静态属性,如非静态属性.

结论

不,您无法在静态和非静态访问和写入之间切换.