Last active
December 17, 2015 03:08
-
-
Save jk/5540659 to your computer and use it in GitHub Desktop.
Compatible version of PHP 5.4's JsonSerializable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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