3v4l.org

run code in 200+ php & hhvm versions
Bugs & Features
<?php class A implements JsonSerializable { protected $a = array(); public function __construct() { $this->a = array( new B, new B ); } public function jsonSerialize() { return $this->a; } } class B implements JsonSerializable { protected $b = array( 'foo' => 'bar' ); public function jsonSerialize() { return $this->b; } } $foo = new A(); $json = json_encode($foo); var_dump($json); class Example implements JsonSerializable { private $_data = array(); public function getData($key = null) { if (is_null($key)) { return $this->_data; } if (array_key_exists($key, $this->_data)) { return $this->_data[$key]; } return null; } public function setData($key, $value = null) { if (is_array($key)) { if (!is_null($value)) { throw new Exception('When setting data in bulk, the value argument must be null'); } $this->_data = $key; return $this; } $this->_data[(string)$key] = $value; return $this; } public function jsonSerialize() { return $this->_data; } } $example = new Example(); $example->setData(array( 'first' => 1, 'second' => 2, ))->setData('third', 3); var_dump(json_encode($example)); $example2 = new Example(); $example3 = new Example(); $example2->setData(array( 'banana' => 'yellow', )); $example3->setData(array( 'apple' => 'red', )); $arr = array( $example, $example2, $example3, ); var_dump(json_encode($arr));
Output for 5.4.0 - 7.2.0
string(29) "[{"foo":"bar"},{"foo":"bar"}]" string(32) "{"first":1,"second":2,"third":3}" string(70) "[{"first":1,"second":2,"third":3},{"banana":"yellow"},{"apple":"red"}]"
Output for 5.3.0 - 5.3.29
Fatal error: Interface 'JsonSerializable' not found in /in/5A0i0 on line 4
Process exited with code 255.
Output for 5.0.5 - 5.2.17
Fatal error: Interface 'JsonSerializable' not found in /in/5A0i0 on line 3
Process exited with code 255.
Output for 5.0.0 - 5.0.4
Fatal error: Class 'JsonSerializable' not found in /in/5A0i0 on line 3
Process exited with code 255.
Output for 4.4.2 - 4.4.9
Parse error: syntax error, unexpected T_STRING, expecting '{' in /in/5A0i0 on line 3
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/5A0i0 on line 3
Process exited with code 255.
Output for 4.3.2 - 4.3.4
Parse error: parse error, expecting `'{'' in /in/5A0i0 on line 3
Process exited with code 255.