(PHP 5, PHP 7)
Interface, um Objekte als Arrays ansprechen zu können
Beispiel #1 Basisnutzung
<?php
class Obj implements ArrayAccess {
private $container = array();
public function __construct() {
$this->container = array(
"eins" => 1,
"zwei" => 2,
"drei" => 3,
);
}
public function offsetSet($offset, $value) {
if (is_null($offset)) {
$this->container[] = $value;
} else {
$this->container[$offset] = $value;
}
}
public function offsetExists($offset) {
return isset($this->container[$offset]);
}
public function offsetUnset($offset) {
unset($this->container[$offset]);
}
public function offsetGet($offset) {
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
)
)