时间:2021-07-01 10:21:17 帮助过:8人阅读
class MOrder extends SModel{
protected static $handle; //单例句柄
private function __construct(){
//something
}
/**
* 获取本类单例的方法,公开
*
* @return MOrder
*/
public static function instance() {
if(self::$handle){
return self::$handle;
}
$class = __CLASS__;
self::$handle = new $class();
return self::$handle;
}
//otherthing
}
5.3增加延迟静态绑定(这个词真别扭)
代码实现如下
class SModel {
/**
* 获取单例句柄,返回具体模型类的实例对象
*/
protected static function instance() {
if(static::$handle){
return static::$handle;
}
$class = get_called_class();
static::$handle = new $class();
return static::$handle;
}
//父类something
}
class MGoods extends SModel{
/**
* 获取本类单例的方法,公开
* @return MGoods
*/
public static function instance(){
return parent::instance();
}
protected static $handle; //单例句柄
protected function __construct(){
//something
}
//otherthing
}
通过修改,子类的实现代码减少一部分,转由父类实现
实话说,仍很麻烦,如果PHP自己实现singleton就好了.
http://www.bkjia.com/PHPjc/678027.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/678027.htmlTechArticle5.3以前也可实现,但代码较繁琐, 如下: class MOrder extends SModel{ protected static $handle; //单例句柄 private function __construct(){ //something } /** * 获取本类...