Home > php教程 > php手册 > 利用好PHP5.3的新特性,实现单例模式

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

WBOY
Release: 2016-06-13 09:45:25
Original
928 people have browsed it

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


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template