I have a project where last developer forgot to serialize objects before storing them into database. Now I have:
stdClass::__set_state(array(
'id' => '1',
'name' => 'John',
'first_name' => 'John',
'middle_name' => 'Montel',
))
I want to do that in professional way and get back object from this variable. I want to access this object data in classic object accessing way $obj->name; I know it's pretty easy to do when object is serialized before. But now I have what I have.
Did a google research for 2 hours - have no ideas for now. Thanks for any help !
That is actually a serialized form obtained using var_export, which returns valid PHP code. From the manual:
var_export — Outputs or returns a parsable string representation of a variable
If the class name in the serialized string would have been 'X', like 'X::__set_state...', you could have defined the '__set_state' method in 'X' and the code would be:
$serializedObj = "X::__set_state(array('id' => '1','name' => 'John',...))";
eval('$myObj = '.$serializedObj).';'
after which you could do:
$name = $myObj->name;
Since the class is 'stdClass', you have 2 options in my opinion:
stdClass::__set_state(
and the last )
in your variable with empty string and eval
the remaining array.stdClass
with you own class X
and define the __set_state
method in X
.