- var_dump: documentation ( source)
- trigger_error: documentation ( source)
<?php
class A implements ArrayAccess, IteratorAggregate {
private $_value = null;
public function __construct($value) {
$this->setValue($value);
}
/** {@inheritDoc} */
public function offsetGet($offset) {
if (!isset($this->_value[$offset])) {
trigger_error('The offset "' . $offset . '" is not defined for this variable', E_USER_NOTICE);
return null;
}
if (!$this->_value[$offset] instanceof self) {
$this->_value[$offset] = new self($this->_value[$offset]);
}
return $this->_value[$offset];
}
/** {@inheritDoc} */
public function offsetSet($offset, $value) {
if (!$value instanceof self) {
$value = new self($value);
}
$this->_value[$offset] = $value;
}
/** {@inheritDoc} */
public function offsetExists($offset) {
return isset($this->_value[$offset]);
}
/** {@inheritDoc} */
public function offsetUnset($offset) {
unset($this->_value[$offset]);
}
public function getValue() {
return $this->_value;
}
public function setValue($value) {
$this->_value = $value;
return $this;
}
public function getIterator() {
if ($this->_value instanceof Traversable) {
return new IteratorIterator($this->_value);
}
if (is_array($this->_value)) {
return new ArrayIterator($this->_value);
}
trigger_error('Variable not iterable', E_USER_WARNING);
return new EmptyIterator;
}
public function __toString() {
return (string) $this->getValue();
}
}
$a = new A([]);
$a['caca'] = 'prout';
$a['pipi'] = 'chouette';
foreach ($a as $k => $v) {
var_dump([$k, (string) $v]);
}
$a = new A('test');
foreach ($a as $k => $v) {
var_dump([$k, (string) $v]);
}
$a = new A(new ArrayObject(['variable', 'totally' => 'iterable']));
foreach ($a as $k => $v) {
var_dump([$k, (string) $v]);
}