1,PHP的回调函数是一个很有用的语法,可以将业务对象与附加其上的处理逻辑隔离开来,这也是观察者模式的一种实现。
代码
<?
php
class 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 " ));
?>
class 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 " ;
};
print " loggint({ $product ->name})\n " ;
};
2,PHP5.3以前的版本是没有package这个语法的,一般是用文件夹来进行类文件的分隔,然后用require_once或include_once来将文件包含来。Include和require这两种方法的差异在于对错误的处理不同。Require包含进来的文件如果出错则会导致整个程序挂掉,而include则只会产生警告信息,并不会导致调用脚本挂掉。因此,从安全性来讲,用require_once更好。我检查了手头的代码,发现还是有一些地方用了include_once,这一点上应该改改。