您的位置:首页 > 编程语言 > PHP开发

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息