Look at the following event class
classEvent {protected Static $listens=Array(); /** [Listen register listener Event] * @param [string] $event [Event Name] * @param [callback] $callback [Event Content] * @param [BOOL] $once [is a one-time event, false by default]*/ Public Static functionListen$event,$callback,$once=false){ if(!is_callable($callback))return false; Self::$listens[$event][] =Array(' Callback ' =$callback, ' once ' =$once); return true; } //Disposable Events Public Static functionOne$event,$callback){ returnSelf::listen ($event,$callback,true); } Public Static functionRemove$event,$index=NULL){ if(Is_null($index)) unset(Self::$listens[$event]); Else unset(Self::$listens[$event][$index]); } Public Static functionTrigger () {//no parameters (pass events) Exit if(!Func_num_args())return; //an array of event names $args=Func_get_args(); //assigns the function name (callback) to the $event $event=Array_shift($args); //detects if the event has been registered, and does not exit if(!isset(Self::$listens[$event]))return false; foreach(Self::$listens[$event] as $index=$listen){ $callback=$listen[' Callback ']; $listen[' Once '] && self::remove ($event,$index); Call_user_func_array($callback,$args); } } }
This class contains the registration, triggering, and removal methods of the event.
An event named Walk is added below, and the action of the event is output "I am WALKING...N" after execution. The event is stored in the $listens array.
function ($a= ',$b= ') { echo "I am WALKING...N". $a . $b
Triggering Walk events
Event::trigger (' walk ');
You can also pass in parameters.
If you do not remove the event, the trigger is executed once.
Once the one-time event is executed once it is destroyed. Call again without any reaction.
function () { echo "run...once"Event:: Trigger (' Walkonce ',true); // The call returned false because it has already been executed Event::trigger (' walkonce ');
Event Handling in PHP