发表时间: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就好了.
上一篇:PHP类和对象函数实例详解
CI框架连接数据库配置操作以及多数据库操作
C语言关键字及其解释介绍 C语言32个关键字详解
asp 简单读取数据表并列出来 ASP如何快速从数据库读取大量数据
C语言中sizeof是什么意思 c语言里sizeof怎样用法详解
将视频设置为Android手机开机动画的教程
IcePHP框架中的快速后台中的通用CRUD功能框架
java中的info是什么意思
PHP中include和require区别之我见
PHP中的魔术方法 :__construct, __destruct , __call, __callStatic,__get, __set, __isset, __unset , __sleep,
PHP中的(++i)前缀自增 和 (i++)后缀自增
2014-09-05
2014-09-05
2022-03-22
2014-09-05
2022-03-17
2017-05-10
2022-03-17
2014-09-05
2022-03-21
2022-03-22