Monday, February 21, 2011

object serialization in PHP (using __sleep)

I am having a difficult time getting object serialization to work properly. According to the documentation, I need to return an array of the variable names I want to serialize from the __sleep function. I did this, but as you can see from the first line of the output, my 50 is nowhere to be found. And when I attempt to unserialize that, the resulting object also does not have the correct value in $myid

header('Content-Type: text/plain');

class Test {
    public $myid;

    function __contstruct($id) {
        $this->myid = $id;
    }

    function __sleep() {
        return array('myid');
    }
}

$test = new Test(50);

$serialized = serialize($test);
echo "serialized to: $serialized\n";

$test2 = unserialize($serialized);

echo "this should be 50: ";
var_dump($test2->myid);

Here is the output:

serialized to: O:4:"Test":1:{s:4:"myid";N;}

this should be 50: NULL

I tried removing the __sleep function from the class, but I get the same result. Whats going on here??

From stackoverflow
  • That's because your constructor has a typo

    function __contstruct($id) {
    --------------^ Right there
    

    Fix that and it all works just fine ;)

    Chris : Unbelievable. I spent the last 3 hours on this, and it was a typo!? :) Thanks though, appreciate it.

0 comments:

Post a Comment