首页 > 编程 > PHP > 正文

php单例模式详解

2019-11-11 03:52:44
字体:
来源:转载
供稿:网友

单例模式的三个要点:

1.需要一个保存类的唯一实例的静态成员变量

PRivate static $_instance;

2.构造函数和克隆函数必须声明为私有的,防止外部程序new类从而失去单例模式的意义

private function __construct() { } private function __clone() { trigger_error('Clone is not allow!',E_USER_ERROR);}//覆盖__clone()方法,禁止克隆

3.必须提供一个访问这个实例的公共的静态方法(通常为getInstance方法),从而返回唯一实例的一个引用

public static function getInstance() { if(! (self::$_instance instanceof self) ) { self::$_instance = new self(); } return self::$_instance; }

在基类中使用后期绑定

public static function getInstance() { if(! (self::$_instance instanceof self) ) { self::$_instance = new static(); } return self::$_instance; }

可以使用后期静态绑定,在基类里实现,其他使用子类继承。

下面是一个完整的例子

class BaseSingle{ public static $_instance; private function __construct() { } public static function getInstance() { if(! self::$_instance instanceof self){ self::$_instance = new Static(); } return self::$_instance; } public function __clone() { } public function getData() { echo __CLASS__.",data222"; }}class Service extends BaseSingle{ public function getData(){ echo __CLASS__.",data..."; }}

以上例程会输出:

Service,data...
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表