<?php
//php回调、匿名函数、闭包 事例
class Product{
public $name;
public $price;
function __CONSTRUCT($name,$price){
$this->name = $name;
$this->price = $price;
}
}
class ProcessSale{
private $callbacks;
public function registerCallback($callback){
if(!is_callable($callback)){
throw new Exception("Error Processing Request", 1);
}
$this->callbacks[] = $callback;
}
public function sale($product){
print "{$product->name}:Processing <br>";
foreach ($this->callbacks as $callback) {
call_user_func($callback,$product);
}
}
}
class Totalizer{
static function warnAmount($amt){
$count = 0;
return function ($product) use ($amt,&$count){
$count += $product->price;
print "count : $count <br>";
if($count > $amt){
print "high price reached: {$count} <br>";
}
};
}
}
$processor = new ProcessSale();
$processor->registerCallback(Totalizer::warnAmount(8));
$processor->sale(new Product("shoes",6));
$processor->sale(new Product("coffes",6));
action
本站未注明转载的文章均为原创,并采用
CC BY-NC-SA 4.0授权协议,
转载请注明来源,谢谢!如本站内容对你有所帮助的话,欢迎订阅关注
邢栋博客,唠嗑(分享)每日的折腾经历。
已有 0 条评论