Znalostná bázaCentrum skúšok
SKSlovenčina
Vybrať jazyk13

CKTIS / PHP

ArrayAccess

Metódy offsetExists, offsetGet, offsetSet a offsetUnset definujú operácie s hranatými zátvorkami.

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

Syntax

class Bag implements ArrayAccess

Metódy offsetExists, offsetGet, offsetSet a offsetUnset definujú operácie s hranatými zátvorkami. Zápis [] aj výslovné [null] odovzdajú index null. O pripojení prvku rozhoduje implementácia offsetSet. Implementácia určí, či je uložené null prítomné. Rozhranie samo nezabezpečí prechod ani 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"]

Príklady

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

Výsledok

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

Zdroje