我最近读到有关在 PHP 中调用作用域和作用域解析运算符 (::) 的内容。有两种变体:实例调用和静态调用。考虑以下听力:
<?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()
of 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