Bene, la domanda è: da dove vuoi impedire di scrivere?
Il primo passo è fare la matrice protetto o privato impedisce la scrittura al di fuori del campo di applicazione oggetto:
protected $arrArray = array();
Se da "fuori" della matrice, un getter ti farà bene. O:
public function getArray() { return $this->arrArray; }
E accedervi come
$array = $obj->getArray();
o
public function __get($name) {
return isset($this->$name) ? $this->$name : null;
}
E accedervi piace:
$array = $obj->arrArray;
Si noti che non restituiscono i riferimenti. Quindi non è possibile modificare la matrice originale al di fuori dell'ambito dell'oggetto. È possibile modificare la matrice stessa ...
Se è davvero necessario un array completamente immutabile, è possibile utilizzare un oggetto utilizzando ArrayAccess
...
Oppure, si potrebbe semplicemente estendere ArrayObject
e sovrascrivere tutti i metodi di scrittura:
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');
}
}
Quindi, è sufficiente fare $this->arrArray
un'istanza dell'oggetto:
public function __construct(array $input) {
$this->arrArray = new ImmutableArrayObject($input);
}
Sostiene ancora più serie come usi:
count($this->arrArray);
echo $this->arrArray[0];
foreach ($this->arrArray as $key => $value) {}
Ma se si tenta di scrive ad esso, si otterrà una LogicException
...
Oh, ma rendersi conto che, se avete bisogno di scrivere ad esso, tutto quello che dovete fare (all'interno dell'oggetto) è fare:
$newArray = $this->arrArray->getArrayCopy();
//Edit array here
$this->arrArray = new ImmutableArrayObject($newArray);
Se voglio avere la mia matrice immutabile caricare se stesso con i dati sulla creazione sovrascriverei la funzione __construct, chiamare il costruttore genitore, ma come posso impostare cosa contiene l'oggetto? –
Ottima risposta! Ma si noti che un array può contenere oggetti: Ogni oggetto viene restituito come riferimento e può essere cambiato, anche con la classe immutabile: '$ a = new ImmutableArrayObject ((oggetto) [ 'foo' => 'bar']); $ b = $ a [0]; $ b-> foo = 'changed'; ' – Philipp