Ole K. Ole K. - 2 months ago 12
PHP Question

Trigger an event when a function is called in a class

Is is possible in PHP to trigger an event whenever a function in a class is called, without adding it to every function in the class?

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();
?>

Answer

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! :)

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:

(simplified example)

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;
     }

 }

Example:

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

 $t->a();