在方法调用之前调用函数

daq*_*aty 6 php

设计问题/ PHP:我有一个方法类.当调用类中的任何方法时,我想随时调用外部函数.我想把它变成通用的所以当我添加另一个方法时,流程也适用于这个方法.

简化示例:

<?php

function foo()
{
    return true;
}

class ABC {
    public function a()
    {
        echo 'a';
    }
    public function b()
    {
        echo 'b';
    }
}

?>
Run Code Online (Sandbox Code Playgroud)

我需要在调用a()或b()之前调用foo().

我怎样才能做到这一点?

Mar*_*ker 7

保护你的方法,使它们不能从类外部直接访问,然后使用magic __call()方法来控制对它们的访问,并在调用你的foo()后执行它们

function foo()
{
    echo 'In pre-execute hook', PHP_EOL;
    return true;
}

class ABC {
    private function a()
    {
        echo 'a', PHP_EOL;
    }
    private function b($myarg)
    {
        echo $myarg, ' b', PHP_EOL;
    }

    public function __call($method, $args) {
        if(!method_exists($this, $method)) {
            throw new Exception("Method doesn't exist");
        }
        call_user_func('foo');
        call_user_func_array([$this, $method], $args);
    }
}

$test = new ABC();
$test->a();
$test->b('Hello');
$test->c();
Run Code Online (Sandbox Code Playgroud)

  • 如果扩展 ABC 类并且 ABC 类使用父类方法,则不起作用。它到达 call_user_func_array 并生成方法未找到异常。 (2认同)