<?php //单例模式 class site { //属性 public $siteName; //本类的静态实例 protected static $instance = null; //禁用掉构造器 private function __construct($siteName) { $this->siteName = $siteName; } //获取本类唯一实例 public static function getInstance($siteName='php中文网') { if (!self::$instance instanceof self){ self::$instance = new self($siteName); } return self::$instance; } } //用工厂模式来生成本类的单一实例 class Factory { //创建指定类的实例 public static function create() { return site::getInstance('www.php.cn'); } } //对象注册树 /** * class Register * 1:注册:set(),把对象挂在树上 * 1:注册:get(),把对象取下来用 * 1:注册:_unset(),把对象吃掉 */ class Register { //创建对象池:数组 protected static $objects = []; //生成对象并上树 public static function set($alias,$object){ self::$objects[$alias] = $object; } //从树上取下对象 public static function get($alias){ return self::$objects[$alias]; } //把树上的对象吃掉 public static function _unset($alias){ unset(self::$objects[$alias]); } } //将site类的实例上树,放对象池 Register::set('site',Factory::create()); //从树上取一个对象下来 $obj = Register::get('site'); //查看一下这个对象 var_dump($obj); echo $obj->siteName;
一定用下面这种方法进行访问:
localhost/demo/pattern.php