Skip to content

Instantly share code, notes, and snippets.

@jk
Last active December 17, 2015 03:08
Show Gist options
  • Select an option

  • Save jk/5540659 to your computer and use it in GitHub Desktop.

Select an option

Save jk/5540659 to your computer and use it in GitHub Desktop.
Compatible version of PHP 5.4's JsonSerializable
<?php
if (!interface_exists('JsonSerializable')) {
define('IJsonSerializable', false);
// inline interface.JsonSerializable.php
interface JsonSerializable {
public function jsonSerialize();
}
} else {
define('IJsonSerializable', true);
}
class ArrayValue implements JsonSerializable {
public function __construct(array $array) {
$this->array = $array;
$this->otherArray = $array;
}
public function jsonSerialize() {
return $this->array;
}
}
$array = array(1, 2, 3);
$obj = new ArrayValue($array);
if (!IJsonSerializable) {
echo json_encode($obj->jsonSerialize()).PHP_EOL;
} else {
echo json_encode($obj).PHP_EOL;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment