每日学习笔记(9)
时间:2010-09-27 来源:Phinecos(洞庭散人)
1,PHP的回调函数是一个很有用的语法,可以将业务对象与附加其上的处理逻辑隔离开来,这也是观察者模式的一种实现。
代码 <?phpclass Product
{
public $name;
public function __construct($name)
{
$this->name = $name;
}
}
class Processor
{
private $callbacks = array();
public function registerCallback($callback)
{
if ( !is_callable($callback)) {
throw new Exception("not callable");
}
$this->callbacks[] = $callback;
}
public function process($product)
{
foreach($this->callbacks as $callback) {
call_user_func($callback, $product);
}
}
}
class Mailer
{
public function sendMail($product)
{
print "mailing ({$product->name})\n";
}
}
$logger = create_function('$product', 'print "loggint({$product->name})\n";');
$processor = new Processor();
$processor->registerCallback($logger);
$processor->registerCallback(array(new Mailer(), "sendMail"));
$processor->process(new Product("pen"));
?>
在PHP5.3中还引入了匿名函数,因此上面的日志函数可以用下述形式来代替:
$logger = function($product) {print "loggint({$product->name})\n";
};
相关阅读 更多 +