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) {
$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"]);
?>
Das oben gezeigte Beispiel erzeugt eine ähnliche Ausgabe wie:
bool(true) int(2) bool(false) string(7) "Ein Wert"