- substr: documentation ( source)
- var_dump: documentation ( source)
- strpos: documentation ( source)
- var_export: documentation ( source)
- rand: documentation ( source)
<?php
class Foo {
protected $prot;
public $pub;
public function init(){
$this->prot = rand(1,9);
$this->pub = rand(1,9);
}
}
function dehydrate($obj){
$class = get_class($obj);
$exp = var_export($obj,1);
return eval('return '.substr($exp,strpos($exp,'(')+1,-1).';');
}
function hydrate($class,$dry=null){
static $hydrators = array();
$h = '_Hydrator__'.$class;
if (empty($hydrators[$class])) {
eval('class '.$h.' extends '.$class.' {
static function __hydrate(array $array) {
$o = new '.$class.'();
foreach ($array as $prop_name => $prop_value) $o->$prop_name = $prop_value;
return $o;
}
}
');
$hydrators[$class] = true;
}
return $dry?$h::__hydrate($dry):null;
}
$a = new Foo();
$a->init();
$dry = dehydrate($a);
hydrate('Foo');
var_dump(
hydrate('Foo',$dry)
);