CKTIS / PHP
ArrayAccess
Implement offsetExists, offsetGet, offsetSet and offsetUnset to define bracket operations on an object.
Version: PHP 8.4; repository runtime, production runtime not attested
Syntax
class Bag implements ArrayAccessImplement offsetExists, offsetGet, offsetSet and offsetUnset to define bracket operations on an object. Both empty brackets and an explicit [null] send a null offset. The offsetSet implementation decides whether that means append. The implementation decides whether a stored null counts as present. ArrayAccess alone does not provide iteration or 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"]
Examples
<?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]]);
Result
["A",true,false,false] ["A","B"]