<?php
// The JSON extension wasn't bundled with PHP until version 5.2.0
if (version_compare(PHP_VERSION, '5.1.6', '<=')) exit('PHP version not supported: json_decode() not available');
// Stop 3v4l.org from showing parse errors in old PHP versions without support for classes or interfaces
else {$_ = __COMPILER_HALT_OFFSET__; eval(substr(file_get_contents(__FILE__), $_ + 2));} __halt_compiler();?>
// Polyfill JsonSerializable
if (!interface_exists('JsonSerializable', FALSE)) {
interface JsonSerializable {
public function jsonSerialize();
}
function json_serialize(JsonSerializable $object) {
return json_encode($object->jsonSerialize());
}
}
interface JsonUnserializable extends JsonSerializable {
public function jsonUnserialize($json);
}
class User implements JsonUnserializable {
private $_name;
public function __construct($name = NULL) {
$this->setName($name);
}
public function setName($name) {
$this->_name = $name;
}
public function getName() {
return $this->_name;
}
public function jsonSerialize() {
return array('name' => $this->getName());
}
public function jsonUnserialize($json) {
$this->setName($json->name);
}
}
function json_unserialize($json, $className) {
if (version_compare(PHP_VERSION, '5.3.9', '>=')) {
$isUnserializable = is_a($className, 'JsonUnserializable', TRUE);
} else {
$isUnserializable = new $className instanceof JsonUnserializable;
}
if ($isUnserializable) {
$object = new $className;
$object->jsonUnserialize(json_decode($json));
return $object;
} else {
return FALSE;
}
}
if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
assert(json_encode(new User('Bar')) === '{"name":"Bar"}');
} else {
assert(json_serialize(new User('Bar')) === '{"name":"Bar"}');
}
$user = json_unserialize('{"name":"Foo"}', 'User');
var_dump($user->getName());