时间:2021-07-01 10:21:17 帮助过:16人阅读
主要思路实现ArrayAccess接口和__get,__set魔术方法
classArrObjectimplementsArrayAccess {private$_data;
    publicfunction__construct($data){$this->_data = $data;
    }
    publicfunctionoffsetGet($offset){return ($this->offsetExists($offset) ? $this->_data[$offset] : null);
    }
    publicfunctionoffsetSet($offset, $value){$this->_data[$offset] = $value;
    }
    publicfunctionoffsetExists($offset){returnisset($this->_data[$offset]);
    }
    publicfunctionoffsetUnset($offset){if($this->offsetExists($offset)){
            unset($this->_data[$offset]);
        }
    }
    publicfunction__get($offset){return ($this->offsetExists($offset) ? $this->_data[$offset] : null);
    }
    publicfunction__set($offset, $value){$this->_data[$offset] = $value;
    }
}测试:
$data  = array('a'=>'a','b'=>'b','c'=>'c');
$test  = new ArrObject($data);
echo$test['a']; //aecho$test->a;   //a以上就介绍了 PHP实现对象属性按数组方式访问,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。