3v4l.org

run code in 300+ PHP versions simultaneously
<?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));

preferences:
65.12 ms | 402 KiB | 5 Q