Base de conocimientosCentro de exámenes
ESEspañol
Elegir idioma13

CKTIS / PHP

ArrayAccess

Los métodos offsetExists, offsetGet, offsetSet y offsetUnset definen las operaciones con corchetes.

Versión: PHP 8.4; repository runtime, production runtime not attested

Sintaxis

class Bag implements ArrayAccess

Los métodos offsetExists, offsetGet, offsetSet y offsetUnset definen las operaciones con corchetes. Tanto [] como [null] explícito pasan el índice null. La implementación de offsetSet decide si añade un elemento. La implementación decide si un null almacenado existe. La interfaz por sí sola no aporta iteración ni 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"]

Ejemplos

<?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]]);

Resultado

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

Fuentes