从PHP 5.3版开始,我们可以call static method in a variable class这样:
class A
{
public static function foo()
{
echo 'bar';
}
}
$myVariableA = A::class;
$myVariableA::foo(); //bar
因此,鉴于以下示例,我想了解为什么B类有效,而C类没有:
class A
{
public static function foo()
{
echo 'bar';
}
}
class B
{
protected $myVariableA;
public function __construct()
{
$this->myVariableA = A::class;
}
public function doSomething()
{
$myVariableA = $this->myVariableA;
return $myVariableA::foo(); //bar (no error)
}
}
class C
{
protected $myVariableA;
public function __construct()
{
$this->myVariableA = A::class;
}
public function doSomething()
{
return $this->myVariableA::foo(); //parse error
}
}
$b = new B;
$b->doSomething();
$c = new C;
$c->doSomething();
请注意我不尝试在此处解决问题,但我想了解其确切原因(如果可能,请参阅实施细节)。