话不多说,直接上代码:
<?php
namespace DesignPattern;
/**
* php设计模式之单例模式
*/
class SingleInstance
{
private static $instance = null;
private function __construct(){}
public static function getInstance()
{
if(is_null(self::$instance)){
self::$instance = new self();
return self::$instance;
}
else{
return self::$instance;
}
}
}
$instance1 = SingleInstance::getInstance();
var_dump($instance1);
$instance2 = SingleInstance::getInstance();
var_dump($instance2);
/**
打印值为:
/Users/icarus/Code/php/SingleInstance.php:29:
class DesignPatternSingleInstance#1 (0) {
}
/Users/icarus/Code/php/SingleInstance.php:31:
class DesignPatternSingleInstance#1 (0) {
}
*/