ArrayAccess arayüzü(PHP 5, PHP 7, PHP 8)
Nesnelere birer dizi olarak erişmeyi sağlayan arayüz.
Örnek 1 Temel kullanım
<?php
class Obj implements ArrayAccess {
public $container = [
"bir" => 1,
"iki" => 2,
"üç" => 3,
];
public function offsetSet($offset, $value): void {
if (is_null($offset)) {
$this->container[] = $value;
} else {
$this->container[$offset] = $value;
}
}
public function offsetExists($offset): bool {
return isset($this->container[$offset]);
}
ublic function offsetUnset($offset): void {
unset($this->container[$offset]);
}
public function offsetGet($offset): mixed {
return isset($this->container[$offset]) ? $this->container[$offset] : null;
}
}
$obj = new Obj;
var_dump(isset($obj["iki"]));
var_dump($obj["iki"]);
unset($obj["iki"]);
var_dump(isset($obj["iki"]));
$obj["iki"] = "Bir değer";
var_dump($obj["iki"]);
$obj[] = 'Ek 1';
$obj[] = 'Ek 2';
$obj[] = 'Ek 3';
print_r($obj);
?>Yukarıdaki örnek şuna benzer bir çıktı üretir:
bool(true)
int(2)
bool(false)
string(7) "Bir değer"
obj Object
(
[container:obj:private] => Array
(
[bir] => 1
[üç] => 3
[iki] => Bir değer
[0] => Ek 1
[1] => Ek 2
[2] => Ek 3
)
)