PHP实现对象属性按数组方式访问
主要思路实现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
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。