3v4l.org

run code in 150+ php & hhvm versions
Bugs & Features
<?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]); }
Output for 5.4.0 - 5.6.28, hhvm-3.10.0 - 3.12.0, 7.0.0 - 7.1.0
array(2) { [0]=> string(4) "caca" [1]=> string(5) "prout" } array(2) { [0]=> string(4) "pipi" [1]=> string(8) "chouette" } Warning: Variable not iterable in /in/AGvhG on line 61 array(2) { [0]=> int(0) [1]=> string(8) "variable" } array(2) { [0]=> string(7) "totally" [1]=> string(8) "iterable" }
Output for 5.1.0 - 5.3.29
Parse error: syntax error, unexpected '[', expecting ')' in /in/AGvhG on line 71
Process exited with code 255.
Output for 5.0.0 - 5.0.5
Parse error: parse error, unexpected '[', expecting ')' in /in/AGvhG on line 71
Process exited with code 255.
Output for 4.4.2 - 4.4.9
Parse error: syntax error, unexpected T_STRING, expecting '{' in /in/AGvhG on line 2
Process exited with code 255.
Output for 4.3.0 - 4.3.1, 4.3.5 - 4.4.1
Parse error: parse error, unexpected T_STRING, expecting '{' in /in/AGvhG on line 2
Process exited with code 255.
Output for 4.3.2 - 4.3.4
Parse error: parse error, expecting `'{'' in /in/AGvhG on line 2
Process exited with code 255.