<?php
class Singleton{
private static $_instance = NULL;
private function __construct(){
echo "construct!";
}
private function __clone(){
echo "clone!";
}
public static function getInstance(){
if(self::$_instance === NULL){ //php5.3后,self可以改成static
self::$_instance = new Singleton(); //$_instance=对象
}
return self::$_instance;
}
public function test(){
echo "test!";
}
}
/*例1:*/
$a=Singleton::getInstance();//实例化类 不能$a = new Singleton();//由于__construct是private类型,所以会报错
$a->test();
//最终输出 "construct!test!"
/*例2:*/
$a=Singleton::getInstance();
$a->test();
$b = Singleton::getInstance();
$b->test();
//最终输出 "construct!test!test!"
举个栗子,感受下self和static(动态绑定)的区别
<?php
class A {
protected static $_instance = null;
protected function __construct() {}
protected function __clone() {}
public function getInstance() {
if (self::$_instance === null) {
self::$_instance = new self();
}
return self::$_instance;
}
}
class B extends A {
protected static $_instance = null;
}
$a = A::getInstance();
$b = B::getInstance();
var_dump($a === $b);//true
class C {
protected static $_instance = null;
protected function __construct() {}
protected function __clone() {}
public function getInstance() {
if (static::$_instance === null) {
static::$_instance = new static;
}
return static::$_instance;
}
}
class D extends C {
protected static $_instance = null;
}
$c = C::getInstance();
$d = D::getInstance();
var_dump($c === $d);//false
将__construct方法设为私有,可以保证这个类不被其他人实例化。但这种写法一个显而易见的问题是:代码不能复用。比如我们在一个一个类继承A,self的引用是在类被定义时就决定的,也就是说,继承了B的A,他的self引用仍然指向A。为了解决这个问题,在PHP 5.3中引入了后期静态绑定的特性。简单说是通过static关键字来访问静态的方法或者变量,与self不同,static的引用是由运行时决定。
http://blog.csdn.net/forevernull/article/details/43670195