PHP的ArrayAccess接口介绍
2024-08-28 11:02:19
在 PHP5 中多了一系列新接口。在 HaoHappy 翻译的你可以了解到他们的应用。同时这些接口和一些实现的 Class 被归为 Standard PHP Library(SPL)。在 PHP5 中加入了很多特性,使类的重载 (Overloading) 得到进一步的加强。ArrayAccess 的作用是使你的 Class 看起来像一个数组(PHP 的数组)。这点和 C# 的 Index 特性很相似。
下面是 ArrayAccess 的定义:
interface ArrayAccess
boolean offsetExists($index)
mixed offsetGet($index)
void offsetSet($index, $newvalue)
void offsetUnset($index)
由于PHP的数组的强大,很多人在写 PHP 应用的时候经常将配置信息保存在一个数组里。于是可能在代码中到处都是 global。我们换种方式?
class Configuration implements ArrayAccess { static private $config;
private $configarray; private function __construct() {
// init
$this->configarray = array("Binzy" => "Male", "Jasmin" => "Female");
} public static function instance() {
//
if (self::$config == null) {
self::$config = new Configuration();
}
return self::$config;
}
//检查一个偏移位置是否存在
function offsetExists($index) {
return isset($this->configarray[$index]);
}
//获取一个偏移位置的值
function offsetGet($index) {
return $this->configarray[$index];
}
//设置一个偏移位置的值
function offsetSet($index, $newvalue) {
$this->configarray[$index] = $newvalue;
}
//复位一个偏移位置的值
function offsetUnset($index) {
unset($this->configarray[$index]);
} } $config = Configuration::instance();
print_r($config);
echo "<br/>";
echo $config['Binzy'];
echo "<br/>";
$config['Binzy'] = '1222';
echo $config['Binzy'];
最新文章
- Ubuntu使用MyEclipse闪退的解决办法
- 烂泥:rsync与inotify集成实现数据实时同步更新
- java中的URLConnection和HttpURLConnection
- git 项目初始化
- 抛砖引玉:关于Android的ListView中CheckBox错乱
- IOS 类别与扩展的区别 (category &; extensions)
- kruskal算法-Pascal
- feed4junit 实现junit4框架体系下数据驱动
- linux配置yum源
- Brainfuck与Ook!编程语言解析与解密
- 【转】open参数O_DIRECT的学习
- Kotlin实现LeetCode算法题之Two Sum
- python3.X中的循环
- 交换机设置IP
- 74.纯 CSS 创作一台 MacBook Pro
- (水题)P1424 小鱼的航程(改进版) 洛谷
- NFine框架全选checkBox列错位
- XMPP增加删除好友
- 用R包中heatmap画热图
- codeforces 434D
热门文章
- Proe 导出PDF Vb.net
- CodeForces 998B Cutting(贪心)
- CI_CD(jenkins)公司实战_未完成版
- python语法基础-网络编程-HTTP协议
- LGOJ4449 于神之怒加强版
- aclocal-1.13: command not found
- iOS运营级B2B服务平台App、自定义图标库、个人中心页面、识别身份证Demo、瀑布流等源码
- iOS路由详解
- PostgreSQL 安装之 CentOS 7 x64 RPM 安装
- 学会使用数据讲故事——Excel研究网络研讨会