好吧,问题是你想从哪里阻止写入?
第一步是使数组受保护或私有,以防止从对象范围之外写入:
protected $arrArray = array();
如果来自数组的“外部”,一个 GETTER 就可以了。要么:
public function getArray() { return $this->arrArray; }
并像访问它一样
$array = $obj->getArray();
或
public function __get($name) {
return isset($this->$name) ? $this->$name : null;
}
然后像这样访问它:
$array = $obj->arrArray;
请注意,它们不返回引用。因此,您不能从对象范围之外更改原始数组。您可以更改数组本身...
如果你真的需要一个完全不可变的数组,你可以使用 ArrayAccess 的 Object ...
或者,您可以简单地扩展 ArrayObject 并覆盖所有写入方法:
class ImmutableArrayObject extends ArrayObject {
public function append($value) {
throw new LogicException('Attempting to write to an immutable array');
}
public function exchangeArray($input) {
throw new LogicException('Attempting to write to an immutable array');
}
public function offsetSet($index, $newval) {
throw new LogicException('Attempting to write to an immutable array');
}
public function offsetUnset($index) {
throw new LogicException('Attempting to write to an immutable array');
}
}
然后,只需将$this->arrArray 设为对象的实例:
public function __construct(array $input) {
$this->arrArray = new ImmutableArrayObject($input);
}
它仍然支持大多数类似数组的用法:
count($this->arrArray);
echo $this->arrArray[0];
foreach ($this->arrArray as $key => $value) {}
但如果你尝试写信给它,你会得到一个LogicException...
哦,但要意识到,如果你需要写它,你需要做的(在对象内)就是做:
$newArray = $this->arrArray->getArrayCopy();
//Edit array here
$this->arrArray = new ImmutableArrayObject($newArray);