class Singleton
{
private static $uniqueInstance;
private $singletonData = '单例类内部数据';
private function __construct()
{
// 构造方法私有化,外部不能直接实例化这个类
}
public static function GetInstance()
{
if (self::$uniqueInstance == null) {
self::$uniqueInstance = new Singleton();
}
return self::$uniqueInstance;
}
public function SingletonOperation(){
$this->singletonData = '修改单例类内部数据';
}
public function GetSigletonData()
{
return $this->singletonData;
}
}
<?php
class HttpService{
private static $instance;
public function GetInstance(){
if(self::$instance == NULL){
self::$instance = new HttpService();
}
return self::$instance;
}
public function Post(){
echo '发送Post请求', PHP_EOL;
}
public function Get(){
echo '发送Get请求', PHP_EOL;
}
}
$httpA = new HttpService();
$httpA->Post();
$httpA->Get();
$httpB = new HttpService();
$httpB->Post();
$httpB->Get();
var_dump($httpA == $httpB);
说明
是不是依然很简单,这里就不多说这种形式的单例了,我们说说另外几种形式的单例
在Java等静态语言中,静态变量可以直接new对象,在声明
instance = new HttpService();。这样可以省略掉GetInstance()方法,但是这个静态变量不管用不用都会直接实例化出来占用内存。这种单例就叫做饿汉式单例模式。