即使方法存在,也在PHP中触发__call()

Cha*_*son 17 php magic-methods

PHP文件说,下面讲__call()魔术方法:

在对象上下文中调用不可访问的方法时会触发__call().

__call()调用实际方法之前,即使方法存在,我是否可以调用?或者,是否有其他钩子我可以实现或提供此功能的另一种方式?

如果它很重要,这是为了static function(我实际上更愿意使用__callStatic).

Pim*_*ger 21

为什么不只是保护所有方法并使用__call()调用它们:

 class bar{
    public function __call($method, $args){
        echo "calling $method";
        //do other stuff
        //possibly do method_exists check
        return call_user_func_array(array($this, $method), $args);
    }
    protected function foo($arg){
       return $arg;
    }
 }

$bar = new bar;
$bar->foo("baz"); //echo's 'calling foo' and returns 'baz'
Run Code Online (Sandbox Code Playgroud)


Ion*_*tan 11

如何保护所有其他方法,并通过__callStatic代理它们?

namespace test\foo;

class A
{
    public static function __callStatic($method, $args)
    {
        echo __METHOD__ . "\n";

        return call_user_func_array(__CLASS__ . '::' . $method, $args);
    }

    protected static function foo()
    {
        echo __METHOD__ . "\n";
    }
}

A::foo();
Run Code Online (Sandbox Code Playgroud)