如何在php中为其他所有函数调用自动调用函数 [英] How to auto call function in php for every other function call

查看:77
本文介绍了如何在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"函数, 这样我就可以得到输出,

How can i call another function before any called function execution? In above case, how can i auto call 'test1' function for every another function call, so that i can get the output as,

test1
test2
test1
test3

目前,我的输出为

test2
test3

我无法在中调用'test1'函数 可能存在的每个函数定义 有很多功能.我需要一种方法 调用前自动调用函数 类的任何功能.

I cannot call 'test1' function in every function definition as there may be many functions. I need a way to auto call a function before calling any function of a class.

任何其他替代方法也可以.

Any alternative way would also be do.

推荐答案

您最好的选择是魔术方法

Your best bet is the magic method __call, see below for example:

<?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
*/

请注意,由于protectedprivatetest2test3在调用它们的上下文中不可见.如果这些方法是公开的,则上面的示例将失败.

Please notice that test2 and test3 are not visible in the context where they are called due to protected and private. If the methods are public the above example will fail.

test1不必声明为private.

ideone.com示例可在此处找到

已更新:将链接添加到ideone,添加带有返回值的示例.

Updated: Add link to ideone, add example with return value.

这篇关于如何在php中为其他所有函数调用自动调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆