- var_dump: documentation ( source)
- json_decode: documentation ( source)
- get_object_vars: documentation ( source)
- json_encode: documentation ( source)
<?php
interface HydrationInterface {
static function dehydrate($obj);
static function hydrate($content);
}
class Foo implements JsonSerializable,HydrationInterface {
protected $secret, $problem;
public function __construct($secret) {
$this->secret = $secret;
}
public function setProblem(Foo $p) {
$this->problem = $p;
}
public function JsonSerialize() {
return self::dehydrate($this);
}
public static function dehydrate($obj) {
return get_object_vars($obj);
}
public static function hydrate($content) {
// var_dump($content); exit();
$o = new static('');
$o->secret = $content->secret;
if( ! is_null($content->problem) ) {
$o->problem = Foo::hydrate($content->problem);
}
return $o;
}
}
$f = new Foo('secret!');
$f->setProblem(new Foo('second level!'));
$h = Foo::hydrate(json_decode('{"secret":"secret!","problem":{"secret":"second level!","problem":null}}'));
var_dump(json_encode($f), $h);