PHP的回调步骤
程序员文章站
2023-12-30 08:45:04
...
PHP的回调方法
回调,不用解释了,我们就来看下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("测试"));
回调,不用解释了,我们就来看下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("测试"));
相关文章
相关视频