1: <?php
2:
3: namespace Xu\Foundation;
4:
5: abstract class Jsonable {
6:
7: /**
8: * Convert the object into something JSON serializable.
9: *
10: * @return array
11: */
12: public function json_serialize() {
13: $items = $this->to_array();
14:
15: foreach ( $items as $key => $value ) {
16: if ( $value instanceof Jsonable ) {
17: $items[$key] = $value->json_serialize();
18: }
19: }
20:
21: return $items;
22: }
23:
24: /**
25: * Convert the class to array.
26: *
27: * @return array
28: */
29: abstract public function to_array();
30:
31: /**
32: * Convert the class instance to JSON.
33: *
34: * @param int $options
35: *
36: * @return string
37: */
38: public function to_json( $options = 0 ) {
39: return json_encode( $this->json_serialize(), $options );
40: }
41: }
42: