我发现了一些奇怪的 PHP 行为,如果有人能解释我为什么这段代码的某些部分有效,而其他部分无效,我很感兴趣。
当类名存储在变量中时,PHP 可以动态创建新类。因为我使用的是现代版本的 PHP (5.5.28),所以它工作得很好。但是我发现了一些我不太了解的奇怪行为。
当类名存储在某个对象的属性中时,就会出现问题。在这种情况下,不能在动态类上调用静态函数:
$this->dynClass::SomeFunction()
失败和($this->dynClass)::SomeFunction()
失败。但是$instance = new $this->dynClass
有效。因此,如果我需要在 上调用静态方法$this->dynClass
,我必须创建一个存储相同字符串的局部变量:$tmp = $this->dynClass
。然后,我可以打电话$tmp::SomeFunction()
我真的不明白这个。这可能是一个错误吗?请有人解释一下。
这是我的示例代码:
<?php
class MyClass {
static function SomeFunction($name){
echo "Hello $name\n";
}
}
MyClass::SomeFunction("World"); //Works fine as it should, prints Hello World
$firstInstance = new MyClass;
$firstInstance::SomeFunction("First"); //prints hello first, no problem
//here comes the interesting part
$dynClass = "MyClass";
$dynClass::SomeFunction("Dynamic"); //Yeah, it works as well
$secondInstance = new $dynClass;
$secondInstance::SomeFunction("Second"); //Hello Second. Fine.
//And here comes the part that I don't understand
class OtherClass {
private $dynClass = "MyClass";
public function test(){
$thirdInstance = new $this->dynClass; //WORKS!
$thirdInstance::SomeFunction('Third'); //Hello Third
//BUT
$this->dynClass::SomeFunction("This"); //PHP Parse error: syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM)
//OK, but then this one should work:
($this->dynClass)::SomeFunction("This"); //same error. WHY??
//The only solution is creating a local variable:
$tmp = $this->dynClass;
$tmp::SomeFunction("Local"); //Hello Local
}
}
$otherInstance = new OtherClass;
$otherInstance->test();
?>