php唯读,PHP中的只读属性?

有没有一种方法可以使对象的只读属性在PHP中?我有一个带有几个数组的对象.我想像通常访问数组一样访问它们

echo $objObject->arrArray[0];

但是我不希望能够在构造完这些数组后对其进行写操作.感觉像构造本地变量的PITA:

$arrArray = $objObject->getArray1();

echo $arrArray[0];

而且无论如何,虽然它使数组保持在原始对象中,但并不能阻止我重写本地数组变量.

解决方法:

好吧,问题是您要阻止写在哪里?

第一步是将数组设置为保护数组或私有数组,以防止从对象范围之外进行写入:

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的对象…

或者,您可以简单地扩展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);

标签:php,oop,readonly

来源: https://codeday.me/bug/20191010/1887005.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值