单例模式保证一个类只有一个实例,并提供一个可以全局访问的点。

我们在数据库中为了节省资源比较常用单例模式。

单例模式几个要点:

a.构造函数必须私有

b.设置保存类实例的静态成员变量

c.提供一个访问函数

d.防止克隆 (__clone私有)

e.防止反序列化单例(__wakeup私有)

实例:

class Singleton {
private static $_instance = null;
private function __construct()
{
    echo 'this is must private';
}

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

private function __clone()
{
    echo 'it not allow clone';
}
	
	private function __wakeup()
	{
	}

public function test()
{
    echo 'my is test';
}
}

客户端调用:

$obj = Singleton::getInstance();
$obj->test();

结果:

this is must privatemy is test

如果直接实例化(报错):

$obj = new Singleton();
$obj->test();

Fatal error: Call to private Singleton::__construct() from invalid context in