PHP实现对象属性按数组方式访问
2016-07-13 15:18
711 查看
主要思路实现ArrayAccess接口和__get,__set魔术方法
测试:
class ArrObject implements ArrayAccess { private $_data; public function __construct($data){ $this->_data = $data; } public function offsetGet($offset){ return ($this->offsetExists($offset) ? $this->_data[$offset] : null); } public function offsetSet($offset, $value){ $this->_data[$offset] = $value; } public function offsetExists($offset){ return isset($this->_data[$offset]); } public function offsetUnset($offset){ if($this->offsetExists($offset)){ unset($this->_data[$offset]); } } public function __get($offset){ return ($this->offsetExists($offset) ? $this->_data[$offset] : null); } public function __set($offset, $value){ $this->_data[$offset] = $value; } }
测试:
$data = array('a'=>'a','b'=>'b','c'=>'c'); $test = new ArrObject($data); echo $test['a']; //a echo $test->a; //a
相关文章推荐
- 一个关于if else容易迷惑的问题
- Python动态类型的学习---引用的理解
- PHP5.2.*防止Hash冲突拒绝服务攻击的Patch
- 深入理解PHP之匿名函数
- JSP/PHP基于Ajax的分页功能实现
- 关于PHP通过PDO用中文条件查询MySQL的问题。
- 什么是设计模式
- PHP数据库长连接mysql_pconnect的细节
- Php Installing An Expansion
- rem : web app适配的秘密武器
- jquery高级应用之Deferred对象
- 关于浮动与清除浮动,你应该知道的
- 数组reduce方法的高级技巧
- php7 读取php.ini[4]
- 土人系列AS入门教程 -- 对象篇
- C#托管堆对象实例包含内容分析
- C#实现获取不同对象中名称相同属性的方法
- PHP+Apache在Windows 9x下的安装和配置