我發現了一些奇怪的PHP行爲,我很感興趣,如果有人能解釋爲什麼這些代碼的某些部分有效,而另一些則不行。具有靜態功能的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();
?>
我不明白PHP的內部,所以我不能告訴你到底爲什麼,但它看起來像它是固定在PHP 7中。使用當前php7測試版的生活實例:http://codepad.viper-7.com/CfJtD3 rfc修復:https://wiki.php.net/rfc/uniform_variable_syntax – Steve