在类中调用函数时触发事件 [英] Trigger an event when a function is called in a class

查看:108
本文介绍了在类中调用函数时触发事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

可以在PHP中触发一个事件,当类中的函数被调用时, p>

Example:

<?php
    class A {
        function xxx() {
            //this function will be called everytime I call another function in this class  
        }

        public static function b() {
            return 'Hello Stackoverflow!';
        }

        public static function c() {
            //I also want this function to trigger the event!
        }
    }

    echo A::b();
?>


推荐答案

AFAIK没有本地语言结构。如果您需要进行调试,建议您深入了解xdebug扩展程序,特别是功能跟踪(真棒!:)

AFAIK there are no native language constructs for this. If you need it for debugging purposes I would advice you to have deeper look into the xdebug extension especially function traces (awesome! :)

另一个想法是实现 __ call() ,并包装所有公共方法。但是,这需要更改代码并具有其他副作用:

Another idea would be to implement __call() in your class and wrap all public methods. But this requires to change the code and has other side effects:

(简化示例)

class Test {

    protected $listeners;

    public function __construct() {
        $this->listeners = array();
    }

    private function a() {
        echo 'something';
    }

    private function b() {
        echo 'something else';
    }

    public function __call($fname, $args) {
        call_user_func_array(array($this, $fname), $args);
        foreach($this->listeners as $listener) {
            $listener->notify('fname was called');
        }
    }

    public function addListener(Listener $listener) {
        $this->listeners[]= $listener;
    }
}

 class Listener {

     public function notify($message) {
         echo $message;
     }

 }

示例:

 $t = new Test();
 $l = new Listener();
 $t->addListener($l);

 $t->a();

这篇关于在类中调用函数时触发事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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