您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

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

2025/1/18 9:23:46发布14次查看
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就好了.
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 } /** * 获取本类...
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product