About PHP callback functions and the use of event callbacks

PHP’s callback mechanism is implemented by using call_user_func (call_user_func_array). Callback functions are a great way to separate some functionality from the core functionality.

The callback mechanism is similar to a notification mechanism and is often used in asynchronous programming. It’s that I ask you to do something, and you’re done, notify me through the interface I provide.

The sample code is as follows.

<?php
// PHP callback function example
class Callback{
	public function call(callable $Callback,$args) {
		call_user_func($Callback, $args);//Core implementation
	}
}

$Callback = new Callback();
$Callback->call(function ($success) {//Pass in the callback function, which is implemented as an anonymous function, or you can pass in the function name, or the method name of the object
	echo "call $success" ;
},999);
//call 999





//Let's look at another example of an event callback, which is often used in event programming using the observer pattern

class Event{
	public $eventMap = array();
    function on($evtname , callable $callable ){ //Register a response callback function on an event
    	$this->eventMap[$evtname][]=$callable;
    }
    function trigger($evtname , $args=null){ //Trigger an event, which is to call all callback functions that respond to this event in a loop
    	foreach ($this->eventMap[$evtname] as $key => $value) {
    		call_user_func_array( $this->eventMap[$evtname][$key] , $args);
    	}
    }
}



$MyClass = new Event();
$MyClass->on('post' , function($a , $b ){
	echo " a = $a ; \n ";
	echo " b = $b ; \n ";
	echo " a + b = ".( $a + $b) . ";\r\n ";
} );

$MyClass->on('post' , function($a , $b ){
	echo " a = $a ; \n ";
	echo " b = $b ; \n ";
	echo " a * b = ".( $a * $b) . ";\r\n ";
} );
 $MyClass->trigger('post' , array( 123 , 321 )  );//Trigger an event
 //a = 123 ; 
 //b = 321 ; 
 //a + b = 444;

 //a = 123 ; 
 //b = 321 ; 
 //a * b = 39483;

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *