If you must access a private/protected class property you can simply use the magic __get
method. Reflection would be way overboard in this case. Whether or not it makes good design sense to use the magic methods in this case depends on your situation, though.
class MyClass
{
private $_items;
public function __get($prop)
{
if ($prop == '_items') {
return $this->_items;
}
throw new OutOfBoundsException;
}
}
UPDATE
After re-reading it seems you simply want your object to behave like an array. To do this you'll need to implement ArrayAccess
and point the relevant methods to the private $_items
property.
class MyClass implements ArrayAccess
{
private $_items = array();
public function __construct() {
$this->_items = array(
"one" => 1,
"two" => 2,
"three" => 3,
);
}
public function offsetSet($offset, $value) {
if (is_null($offset)) {
$this->_items[] = $value;
} else {
$this->_items[$offset] = $value;
}
}
public function offsetExists($offset) {
return isset($this->_items[$offset]);
}
public function offsetUnset($offset) {
unset($this->_items[$offset]);
}
public function offsetGet($offset) {
return isset($this->_items[$offset]) ? $this->_items[$offset] : null;
}
}
And finally, PHP comes with a built-in ArrayObject
class that will make an object behave very much like an array. You could always use that and point the relevent methods at a private $_items
property.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…