我的代码是这样的:
<?php
class A {
public function CallA()
{
echo "callA" . PHP_EOL;
}
public static function CallB()
{
echo "callB" . PHP_EOL;
}
public static function __callStatic($method, $args)
{
echo "callStatic {$method}";
}
}
A::CallA();
Run Code Online (Sandbox Code Playgroud)
但它会回应:
Strict Standards: Non-static method A::CallA() should not be called statically in /vagrant/hades_install/public/test.php on line 21
callA
Run Code Online (Sandbox Code Playgroud)
也就是说,CallA不会遇到功能__callStatic
如果我想__callStatic通过使用调用,我该怎么办?A::CallA()
如文档所述:
__callStatic()在静态上下文中调用不可访问的方法时触发。
CallA()您代码中的方法是可访问的,这就是为什么PHP不使用__callStatic()并且CallA()直接调用是其唯一的选择的原因。
您可以__callStatic()通过使其CallA()无法访问(将其重命名或将其可见性更改为protected或private)或通过直接调用(丑陋的解决方法)来强制调用:
A::__callStatic('CallA', array());
Run Code Online (Sandbox Code Playgroud)
如果选择CallA()保护,则需要实现该方法__call()以CallA()再次调用:
class A {
protected function CallA()
{
echo "callA" . PHP_EOL;
}
public static function CallB()
{
echo "callB" . PHP_EOL;
}
public static function __callStatic($method, $args)
{
echo "callStatic {$method}" . PHP_EOL;
}
public function __call($method, $args)
{
if ($method == 'CallA') {
$this->CallA();
}
}
}
A::CallA();
A::__callStatic('CallA', array());
$x = new A();
$x->CallA();
Run Code Online (Sandbox Code Playgroud)
它输出:
callStatic CallA
callStatic CallA
callA
Run Code Online (Sandbox Code Playgroud)