PHP单例模式

单例模式三大原则:(单例就是一个类,只能拥有一个实例!)
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(){}
}


     

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值