回調,不用解釋了,我們就來看下PHP怎麼實現回調
1.首先建一個對象
class Product{
public $name; //為了方便測試
function __construct($name){
$this->name=$name;
}
}
2.使用回調
class ProcessSale{
private $callbacks;
//設置回調方法
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.測試
$logger = function($product){
print "logging ({$product->name})";
}
$processor = new ProcessSale();
$processor->registerCallBack($logger);
$processor->sale(new Product("測試"));
作者:sunwei-07