访问静态variablefrom类实例
问题描述:
我想用这行代码:访问静态variablefrom类实例
$this->ClassInstance::$StaticVariable;
如果是这种基本设置:
Class foo{
public static $StaticVariable;
}
$this->ClassInstance = new foo();
这是什么是一个分析背后的原因错误?
当这样的:
$ClassInstance = $this->ClassInstance;
$ClassInstance::$StaticVariable;
是完全有效的。
答
在PHP文档
声明类属性或方法为静态,使他们无需类的实例访问。声明为静态的属性无法通过实例化的类对象进行访问(尽管可以使用静态方法)。
答
您可以self::$staticVariable
或foo::$staticVariable
访问它。不需要使用实例。
答
假设你的意思是
Class Foo{
public static $StaticVariable = 42;
}
class Bar {
private $ClassInstance;
public function fn() {
$this->ClassInstance = new Foo();
return $this->ClassInstance::$StaticVariable;
}
}
$bar = new Bar;
echo $bar->fn();
然后this works as of PHP7。在此之前,解析器根本无法解除引用。详情请参阅wiki page linked in the comments to your question。
虽然你可以使用get_class($this->ClassInstance)::$StaticVariable;
。
请参阅https://wiki.php.net/rfc/uniform_variable_syntax –