Das ArrayAccess-Interface

(PHP 5, PHP 7, PHP 8)

Einführung

Interface, um Objekte als Arrays ansprechen zu können

Interface-Übersicht

interface ArrayAccess {
/* Methoden */
public offsetExists(mixed $offset): bool
public offsetGet(mixed $offset): mixed
public offsetSet(mixed $offset, mixed $value): void
public offsetUnset(mixed $offset): void
}

Beispiel #1 Grundlegende Verwendung

<?php
class Obj implements ArrayAccess {
public
$container = [
"eins" => 1,
"zwei" => 2,
"drei" => 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]);
}

public 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["zwei"]));
var_dump($obj["zwei"]);
unset(
$obj["zwei"]);
var_dump(isset($obj["zwei"]));
$obj["zwei"] = "Ein Wert";
var_dump($obj["zwei"]);
$obj[] = 'Anhängen 1';
$obj[] = 'Anhängen 2';
$obj[] = 'Anhängen 3';
print_r($obj);
?>

Das oben gezeigte Beispiel erzeugt eine ähnliche Ausgabe wie:

bool(true)
int(2)
bool(false)
string(7) "Ein Wert"
obj Object
(
    [container:obj:private] => Array
        (
            [eins] => 1
            [drei] => 3
            [zwei] => Ein Wert
            [0] => Anhängen 1
            [1] => Anhängen 2
            [2] => Anhängen 3
        )

)

Inhaltsverzeichnis