Triggering __call() in PHP even when method exists

[亡魂溺海] 提交于 2019-11-29 06:18:29

问题


The PHP documentation says the following about the __call() magic method:

__call() is triggered when invoking inaccessible methods in an object context.

Is there a way I can have __call() called even when a method exists, before the actual method is called? Or, is there some other hook I can implement or another way that would provide this functionality?

If it matters, this is for a static function (and I would actually prefer to use __callStatic).


回答1:


How about just make all your other methods protected, and proxy them through __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();



回答2:


Why not just make all your methods protected and call them using __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'


来源:https://stackoverflow.com/questions/1071894/triggering-call-in-php-even-when-method-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!