PHP设计模式 注册表模式(多个类的注册)
时间:2023-11-20 06:45:13
以前我也写过一个注册表类,不过那一个不能进行多个类的注册,下面用数组对类进行了存储。
<?php
//基础类
class webSite {//一个非常简单的基础类
private $siteName;
private $siteUrl;
function __construct($siteName,$siteUrl){
$this->siteName=$siteName;
$this->siteUrl=$siteUrl;
}
function getName(){
return $this->siteName;
}
function getUrl(){
return $this->siteUrl;
}
}
class registry {//注册表类 单例模式
private static $instance;
private $values=array();//用数组存放类名称
private function __construct(){}//这个用法决定了这个类不能直接实例化
static function instance(){
if (!isset(self::$instance)){self::$instance=new self();}
return self::$instance;
}
function get($key){//获取已经注册了的类
if (isset($this->values[$key])){
return $this->values[$key];
}
return null;
}
function set($key,$value){//注册类方法
$this->values[$key]=$value;
}
}
$reg=registry::instance();
$reg->set("website",new webSite("WEB开发笔记","www.chhua.com"));//对类进行注册
$website=$reg->get("website");//获取类
echo $website->getName();//输出WEB开发笔记
echo $website->getUrl();//输出www.chhua.com
?>
注册表的作用是提供系统级别的对象访问功能。有的同学会说,这样是多此一举,不过小项目中的确没有必要对类进行注册,如果是大项目,还是非常有用的。
标签:设计模式
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
基于Vue3实现日历组件的示例代码
2024-05-29 22:25:16
Python实现读取邮箱中的邮件功能示例【含文本及附件】
2022-10-25 04:37:23
使用HTTP_X_FORWARDED_FOR获取客户端IP的严重后果
2022-06-22 04:44:29
Python入门教程(九)Python字符串介绍
2023-02-05 22:34:43
![](https://img.aspxhome.com/file/2023/8/80488_0s.png)
Python基础之赋值,浅拷贝,深拷贝的区别
2021-06-28 18:39:15
PHP基于rabbitmq操作类的生产者和消费者功能示例
2023-11-23 20:03:03
Selenium+BeautifulSoup+json获取Script标签内的json数据
2023-06-17 09:30:18
python实现远程控制电脑
2022-12-07 21:00:16
python实现从文件中读取数据并绘制成 x y 轴图形的方法
2023-04-09 22:43:41
![](https://img.aspxhome.com/file/2023/5/94005_0s.jpg)
Python反爬实战掌握酷狗音乐排行榜加密规则
2021-05-29 08:05:57
![](https://img.aspxhome.com/file/2023/5/70245_0s.gif)
python mysql实现学生成绩管理系统
2024-01-25 09:28:12
![](https://img.aspxhome.com/file/2023/1/92361_0s.jpg)
python 包之 Pillow 图像处理教程分享
2022-02-22 01:22:48
使用Python解析JSON数据的基本方法
2021-07-03 13:54:21
SQL Server手工插入标识列的方法
2024-01-27 05:41:35
Python中Jieba进行词频统计与关键词提取
2022-02-03 23:08:50
![](https://img.aspxhome.com/file/2023/1/65981_0s.png)
基于python读取.mat文件并取出信息
2021-10-24 12:06:26
![](https://img.aspxhome.com/file/2023/1/75971_0s.png)
js中继承的几种用法总结(apply,call,prototype)
2024-04-16 09:47:25
PJBlog3优化——单击自动输入验证码
2009-05-17 11:03:00
MySQL优化方案参考
2024-01-24 03:28:03
![](https://img.aspxhome.com/file/2023/2/107722_0s.png)
Ubuntu16.04 server下配置MySQL,并开启远程连接的方法
2024-01-17 08:59:10
![](https://img.aspxhome.com/file/2023/5/65705_0s.png)