在类中调用函数时触发事件

Jun*_*ior 5 php events class function

PHP中是否可以在调用类中的函数时触发事件,而不将其添加到类中的每个函数中?

例:

<?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();
?>
Run Code Online (Sandbox Code Playgroud)

hek*_*mgl 14

AFAIK没有本地语言结构.如果您需要它用于调试目的,我建议您深入了解xdebug扩展,尤其是函数跟踪(真棒!:)

另一个想法是__call()在你的类中实现并包装所有公共方法.但这需要更改代码并具有其他副作用:

(简化示例)

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

.

 class Listener {

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

 }
Run Code Online (Sandbox Code Playgroud)

例:

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

 $t->a();
Run Code Online (Sandbox Code Playgroud)