青风百里

PHP 单例工厂类
工厂类本身不创建对象注意使用数组保存对象注意有isset()判断数组中是否存在对象数组中只要有值,就是对象上代码&...
扫描右侧二维码阅读全文
03
2018/10

PHP 单例工厂类

  • 工厂类本身不创建对象
  • 注意使用数组保存对象
  • 注意有isset()判断数组中是否存在对象
  • 数组中只要有值,就是对象
  • 上代码
<?php
class Factory{
    private static $objs = [];
    public static function getInstance($className){
        if(!isset(self::$objs[$className])){
            self::$objs[$className] = new $className;
        }
        return self::$objs[$className];
    }
}

class student{

}

class teacher{

}

$stuObj1 = Factory::getInstance("student");
$stuObj2 = Factory::getInstance("student");
$teaObj1 = Factory::getInstance("teacher");
$teaObj2 = Factory::getInstance("teacher");
echo $stuObj1 == $stuObj2;
echo "<br>";
echo $teaObj1 == $teaObj2;

Last modification:October 3rd, 2018 at 07:09 pm

Leave a Comment