知识屋:更实用的电脑技术知识网站
所在位置:首页 > 编程技术  > PHP编程

利用好PHP5.3的新特性,实现单例模式

发表时间:2014-09-05来源:网络

5.3以前也可实现,但代码较繁琐, 如下:

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就好了.


(免责声明:文章内容如涉及作品内容、版权和其它问题,请及时与我们联系,我们将在第一时间删除内容,文章内容仅供参考)
收藏
  • 人气文章
  • 最新文章
  • 下载排行榜
  • 热门排行榜