小编典典

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

php

Class test{
    function test1()
    {
        echo 'inside test1';
    }

    function test2()
    {
        echo 'test2';
    }

    function test3()
    {
        echo 'test3';
    }
}

$obj = new test;
$obj->test2();//prints test2
$obj->test3();//prints test3

现在我的问题是

在执行任何调用的函数之前,如何调用另一个函数?在上述情况下,我如何才能为每个其他函数调用自动调用“ test1”函数,这样我就可以获得输出,

test1
test2
test1
test3

目前我正在获得输出

test2
test3

我不能在每个函数定义中都调用“ test1”函数,因为可能有很多函数。我需要一种在调用类的任何函数之前自动调用函数的方法。

任何替代方式也可以。


阅读 374

收藏
2020-05-29

共1个答案

小编典典

最好的选择是魔术方法__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的链接,添加带有返回值的示例。

2020-05-29