设计模式php篇(一)————单例模式

时间:2022-12-11 12:14:59

话不多说,直接上代码:

<?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 DesignPattern\SingleInstance#1 (0) {
}
/Users/icarus/Code/php/SingleInstance.php:31:
class DesignPattern\SingleInstance#1 (0) {
}
*/