2017-03-09 109 views
1

我想用这行代码:访问静态variablefrom类实例

$this->ClassInstance::$StaticVariable; 

如果是这种基本设置:

Class foo{ 
    public static $StaticVariable; 
} 

$this->ClassInstance = new foo(); 

这是什么是一个分析背后的原因错误?

当这样的:

$ClassInstance = $this->ClassInstance; 
$ClassInstance::$StaticVariable; 

是完全有效的。

+1

请参阅https://wiki.php.net/rfc/uniform_variable_syntax –

回答

2

您可以self::$staticVariablefoo::$staticVariable访问它。不需要使用实例。

3

假设你的意思是

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;