单例模式:保证一个类仅有一个实例,并提供一个访问它的全局访问点。
定义一个私有的构造方法,可以让类无法从自身外部实例化。
<?php
header("Content-type: text/html; charset=utf-8");
class Singleton{
privatestatic$instance;
privatefunction __construct(){}
staticfunction GetInstance(){
if(empty(self::$instance)){
self::$instance=new Singleton();
}
return self::$instance;
}
}
$s1=Singleton::GetInstance();
$s2=Singleton::GetInstance();
if($s1===$s2){
echo"这是两个相同的实例";
}
else{
echo"这两个实例不同";
}
注意:在unset()该单例对象以后,重新实例化后,里面的属性值还会存在。
转载于:https://blog.51cto.com/here2142/1124269