实现单例的三个关键点:
1、使用一个静态成员来保持一个单例实例
2、一个私有的构造方法使得该类只能在类的内部方法中被实例化
3、在实例化对象的静态方法中,先判断静态变量是否已经被赋值,如果赋值则返回该静态成员如果没有则重新实例化赋值
单例模式:
代码语言:javascript复制class Car{
public static $_instance = null;
private $name;
private function __construct($name){
$this->name = $name;
}
public static function getInstance($name){
if(!self::$_instance){
self::$_instance = new Car($name);
}
return self::$_instance;
}
public function getName(){
return $this->name;
}
}
$car = Car::getInstance("benchi");
$car1 = Car::getInstance("baoma");
print_r($car->getName());
print_r($car->getName()); // 输出 benchibenchi
普通实例化类:
代码语言:javascript复制class Car{
private $name;
public function __construct($name){
$this->name = $name;
}
public function getName(){
return $this->name;
}
}
$car = new Car("benchi");
$car1 = new Car("baoma");
print_r($car->getName());
print_r($car1->getName()); //输出 benchibaoma