您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何在php中为其他所有函数调用自动调用函数

如何在php中为其他所有函数调用自动调用函数

最好的选择是魔术方法__call,请参见以下示例:

<?PHP

class test {
    function __construct(){}

    private function test1(){
        echo "In test1", PHP_EOL;
    }
    private function test2(){
        echo "test2", PHP_EOL;
    }
    protected function test3(){
        return "test3" . PHP_EOL;
    }
    public function __call($method,$arguments) {
        if(method_exists($this, $method)) {
            $this->test1();
            return call_user_func_array(array($this,$method),$arguments);
        }
    }
}

$a = new test;
$a->test2();
echo $a->test3();
/*
* Output:
* In test1
* test2
* In test1
* test3
*/

请注意,test2test3在由于protected和而被调用的上下文中不可见private。如果这些方法是公开的,则上面的示例将失败。

test1不必声明private

ideone.com示例可以在这里找到

添加到ideone的链接添加带有返回值的示例。

php 2022/1/1 18:13:50 有702人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶