最近、PHP でのスコープとスコープ解決演算子 (::) の呼び出しについて読みました。インスタンス呼び出しと静的呼び出しの 2 つのバリエーションがあります。次のリスニングを検討してください。
<?php
class A {
public function __call($method, $parameters) {
echo "I'm the __call() magic method".PHP_EOL;
}
public static function __callStatic($method, $parameters) {
echo "I'm the __callStatic() magic method".PHP_EOL;
}
}
class B extends A {
public function bar() {
A::foo();
}
}
class C {
public function bar() {
A::foo();
}
}
A::foo();
(new A)->foo();
B::bar();
(new B)->bar();
C::bar();
(new C)->bar();
実行結果 (PHP 5.4.9-4ubuntu2.2) は次のとおりです。
I'm the __callStatic() magic method
I'm the __call() magic method
I'm the __callStatic() magic method
I'm the __call() magic method
I'm the __callStatic() magic method
I'm the __callStatic() magic method
(new C)->bar();
を実行する理由__callStatic()
がわかりませんA
? インスタンス呼び出しは bar() メソッドのコンテキストで行うべきですね。PHPの機能ですか?
追加1:
さらに、魔法のメソッドを使用せずに明示的に呼び出すと、すべてが期待どおりに機能します。
<?php
class A {
public function foo() {
echo "I'm the foo() method of A class".PHP_EOL;
echo 'Current class of $this is '.get_class($this).PHP_EOL;
echo 'Called class is '.get_called_class().PHP_EOL;
}
}
class B {
public function bar() {
A::foo();
}
}
(new B)->bar();
この結果:
I'm the foo() method of A class
Current class of $this is B
Called class is B