PHP中的只读属性?

use*_*841 11 php oop readonly

有没有办法在PHP中创建对象的只读属性?我有一个带有几个数组的对象.我想像通常的数组一样访问它们

echo $objObject->arrArray[0];
Run Code Online (Sandbox Code Playgroud)

但我不希望能够在构造之后写入这些数组.感觉就像构建一个局部变量的PITA:

$arrArray = $objObject->getArray1();
echo $arrArray[0];
Run Code Online (Sandbox Code Playgroud)

无论如何,虽然它将数组保持在对象原始状态,但它并不妨碍我重写本地数组变量.

irc*_*ell 25

好吧,问题是你想在哪里阻止写作?

第一步是使数组受保护或私有以防止从对象范围之外写入:

protected $arrArray = array();
Run Code Online (Sandbox Code Playgroud)

如果来自阵列的"外部",GETTER会对你没问题.或者:

public function getArray() { return $this->arrArray; }
Run Code Online (Sandbox Code Playgroud)

并像访问它一样

$array = $obj->getArray();
Run Code Online (Sandbox Code Playgroud)

要么

public function __get($name) {
    return isset($this->$name) ? $this->$name : null;
}
Run Code Online (Sandbox Code Playgroud)

并访问它像:

$array = $obj->arrArray;
Run Code Online (Sandbox Code Playgroud)

请注意,它们不会返回引用.因此,您无法从对象范围之外更改原始数组.你可以改变阵列本身......

如果你真的需要一个完全不可变的数组,你可以使用一个Object ArrayAccess...

或者,您可以简单地扩展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');
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,只需创建$this->arrArray一个对象的实例:

public function __construct(array $input) {
    $this->arrArray = new ImmutableArrayObject($input);
}
Run Code Online (Sandbox Code Playgroud)

它仍然支持大多数数组,如使用:

count($this->arrArray);
echo $this->arrArray[0];
foreach ($this->arrArray as $key => $value) {}
Run Code Online (Sandbox Code Playgroud)

但如果你试着写信给它,你会得到一个LogicException......

哦,但是要意识到如果你需要写它,你需要做的(在对象内)你做的是:

$newArray = $this->arrArray->getArrayCopy();
//Edit array here
$this->arrArray = new ImmutableArrayObject($newArray);
Run Code Online (Sandbox Code Playgroud)