Callback, no need to explain, let’s take a look at how to implement callback in PHP
1. First create an object
class Product{
public $name; //For convenience of testing
function __construct($name){
$this->name=$name;
}
}
2. Use callbacks
class ProcessSale{
private $callbacks;
//Set callback method
function registerCallBack($callback){
If(!is_callable($callback)){
throw new Exception("xxxxxx");
}
$this->callbacks[]=$callback;
}
function sale($product){
Print "{$product->name}:processing n";
foreach($this->callbacks as $callback){
call_user_func($callback,$product);
}
}
}
3. Test
$logger = function($product){
print "logging ({$product->name})";
}
$processor = new ProcessSale();
$processor->registerCallBack($logger);
$processor->sale(new Product("Test"));
Author: sunwei-07