您的位置:首页 > 编程语言 > PHP开发

PHP单例模式

2014-08-12 20:54 239 查看
单例模式三大原则:(单例就是一个类,只能拥有一个实例!)
1.构造函数需要标记为非public[只能声明成私有模式private](防止外部使用new操作符创建对象),单例类不能在其他类中实例化,只能被其自身实例化;
2.拥有一个保存类的实例的静态成员变量$_instance;
3.拥有一个访问这个实例的公共的静态方法
<?php

class single_model{
private $_db;
static $_instance;
private function __construct(){
$this ->_db = mysql_connect('127.0.0.1','root','root') or die(mysql_error());
}
private function __clone(){}

public static function get_instance(){
if(!self::$_instance instanceof self){
self::$_instance = new self();
}
return self::$_instance;
}
public function query($sql){
return mysql_query($sql);
}
public function test(){
echo 11;
}
}

$res = single_model::get_instance()->test();


<?php
class singleton
{
private static $instances;

public function __construct() {
$c = get_class($this);
if(isset(self::$instances[$c])) {
throw new Exception('You can not create more than one copy of a singleton.');
} else {
self::$instances[$c] = $this;
}
}

public function get_instance() {
$c = get_called_class();
if (!isset(self::$instances[$c])) {
$args = func_get_args();
$reflection_object = new ReflectionClass($c);
self::$instances[$c] = $reflection_object->newInstanceArgs($args);
}
return self::$instances[$c];
}

public function __clone() {
throw new Exception('You can not clone a singleton.');
}
}

class singleton_test extends singleton
{
}

$o = singleton_test::get_instance();
print get_class($o);

<?php
/**
+-----------------------------------------
* 四脚猫每日一题-用PHP实现一个单例模式
+-----------------------------------------
* @description   完美的单例模式????
* @author   诺天  thinkercode@sina.com
* @date 2014年5月7日
+-----------------------------------------
*/
class singleton{
public static $instance = null;

/**
* 对象初始化方法,防止继承覆盖和new该类
* @access private
* @return void
*/
final private function __construct(){}

/**
* 获取对象实例
* @access public
* @return object
*/
static public function getInstances(){
if(!(self::$instances instanceof self)){
self::$instance = new self;
}
return self::$instance ;
}

/**
* 让克隆也实现单例
* @access public
* @return void
*/
final public function __clone(){
return self::$instance ;
}

/**
* 让克隆不能使用
* @access private
* @return void
*/
//final private function __clone(){}
}




     
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: