如何将一个函数绑定到另一个函数'在PHP中


How do you bind a function to another function 'event status' in PHP

为了简化类的调试,我想将一个函数绑定到其他函数事件的状态。我目前的设置类似于下面的代码:

class config {
    function __construct($file) {
        $this->functions = array(); // The array with function run/succes information
        if (!empty($file)) {
            $this->checkFile($file);
        }
    }
    public function checkFile($file) {
         $this->functionStatus('run',true);
         if (file_exists($file)) {
            $this->functionStatus('succes',true);
            return true; 
        } else {
            $this->functionStatus('succes',true);
            return false;
        }
     }
    /* Simplified functionStatus function */
    private function functionStatus($name,$value) {
        /* - validations removed -*/
        // Get parent function name
        $callers = debug_backtrace();
        $function = $callers[1]['function'];
         /* - validations removed -*/

        $this->functions[$function][$name] = $value;
    }
}

使用该原则的一个例子:

$config = new config('example.ini');
print var_dump($config->functions);
/* Results in:
array(1) { 
    ["checkFile"]=> array(2) { 
        ["run"]=> bool(true) 
        ["succes"]=> bool(true) 
    } 
} 
*/

虽然这个设置工作良好。我想通过每次创建函数时删除手动放置的$this->functionStatus('run',true)函数来改进它,以保持代码更干净,并防止假设函数没有运行,因为有人忘记在函数的顶部定义functionStatus。对于返回事件的定义也是如此。

*注意,最好的解决方案还应该支持与其他类的绑定有没有办法用PHP完成这个"事件绑定"?

您可以使用__call魔术方法来完成此操作。将所有公共函数更改为私有方法,并在名称前添加前缀,例如

private function internal_checkFile($file) {
    ...
}

然后添加魔法方法:

public function __call($name, $arguments) {
    $this->functionStatus('run', true);
    return call_user_func_array(array($this, "internal_$name"), $arguments);
}