单例模式
<?php
/**
* @Author: Leen
* @Date: 2020-09-18 11:57:41
* @Last Modified By : Leen
*/
class Singleton
{
private static $_instance = null;
private static $num = 0;
private function __construct(){}
private function __clone(){}
public static function getInstance()
{
// if (self::$_instance == null) {
// if (!(self::$_instance instanceof Singleton)) {
if (!(self::$_instance instanceof self)) {
self::$_instance = new self();
self::$num++;
}
echo '<BR>num:'.self::$num;
return self::$_instance;
}
}
$singletonObj = Singleton::getInstance();
$singletonObj2 = Singleton::getInstance();
echo '<BR>singletonObj:';var_dump($singletonObj);
echo '<BR>singletonObj2:';var_dump($singletonObj2);
var_dump($singletonObj===$singletonObj2);
结果:
num:1
num:1
singletonObj:object(Singleton)#1 (0) { }
singletonObj2:object(Singleton)#1 (0) { } bool(true)
两种方法验证是否同一个实例:
1、num数量是否有不一致,如果不一致说明是两个实例。
2、如果不放心第一种,可以使用"==="来判断是否同一个实例。
下面是不同实例的输出结果:
num:1
num:2
singletonObj:object(Singleton)#1 (0) { }
singletonObj2:object(Singleton)#2 (0) { } bool(false)
Author:leedaning
本文地址:https://blog.csdn.net/leedaning/article/details/108665450