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();
?>