Base di conoscenzaCentro esami
ITItaliano
Scegli la lingua13

CKTIS / PHP

ArrayAccess

I metodi offsetExists, offsetGet, offsetSet e offsetUnset definiscono le operazioni con parentesi quadre.

Versione: PHP 8.4; repository runtime, production runtime not attested

Sintassi

class Bag implements ArrayAccess

I metodi offsetExists, offsetGet, offsetSet e offsetUnset definiscono le operazioni con parentesi quadre. Sia [] sia [null] esplicito passano l’indice null. È offsetSet a decidere se aggiungere l’elemento. L’implementazione decide se un null memorizzato è presente. L’interfaccia da sola non fornisce iterazione né Countable.

class Bag implements ArrayAccess { private array $items=[]; public function offsetExists(mixed $k): bool{return array_key_exists($k,$this->items);} public function offsetGet(mixed $k): mixed{return $this->items[$k];} public function offsetSet(mixed $k,mixed $v): void{if($k===null){$this->items[]=$v;}else{$this->items[$k]=$v;}} public function offsetUnset(mixed $k): void{unset($this->items[$k]);} }
$bag=new Bag(); $bag[]="A"; $bag["x"]=null;
$was=isset($bag["x"]); unset($bag["x"]);
echo json_encode([$bag[0],$was,isset($bag["x"]),is_iterable($bag)]);
$bag[null]="B"; echo PHP_EOL,json_encode([$bag[0],$bag[1]]);
["A",true,false,false]
["A","B"]

Esempi

<?php
class Bag implements ArrayAccess { private array $items=[]; public function offsetExists(mixed $k): bool{return array_key_exists($k,$this->items);} public function offsetGet(mixed $k): mixed{return $this->items[$k];} public function offsetSet(mixed $k,mixed $v): void{if($k===null){$this->items[]=$v;}else{$this->items[$k]=$v;}} public function offsetUnset(mixed $k): void{unset($this->items[$k]);} }
$bag=new Bag(); $bag[]="A"; $bag["x"]=null;
$was=isset($bag["x"]); unset($bag["x"]);
echo json_encode([$bag[0],$was,isset($bag["x"]),is_iterable($bag)]);
$bag[null]="B"; echo PHP_EOL,json_encode([$bag[0],$bag[1]]);

Risultato

["A",true,false,false]
["A","B"]

Fonti