Page 1 of 1

problem with serialize and magic method __sleep()

Posted: Mon Jun 05, 2006 8:58 pm
by bg
See code:

Code: Select all

<?php

class test{
	private $prop = 'blah';
	
	public function __sleep(){
		echo 'going to sleep';
	}
}

$test = new test();

echo serialize($test);

?>
The output of this script gives us:

Code: Select all

going to sleepN;
Which is showing us that the object isn't being properly serialized for some reason. If you remove the magic __sleep() function, everything serializes correctly:

Code: Select all

<?php

class test{
	private $prop = 'blah';
	
	/*
	public function __sleep(){
		echo 'going to sleep';
	}
	*/
}

$test = new test();

echo serialize($test);

?>
this gives us the expected output of:

Code: Select all

O:4:"test":1:{s:10:"

Posted: Mon Jun 05, 2006 9:06 pm
by feyd
your implementation of __sleep doesn't return data to be serialized.

Posted: Mon Jun 05, 2006 9:15 pm
by bdlang
According to the PHP manual reference on 'Magic Methods', it would appear as though you haven't defined __sleep() properly. It is expected to return an array. Try:

Code: Select all

class test{
        private $prop = 'blah';
       
        public function __sleep(){
                return array($this->prop);
        }
}

$test = new test();

echo serialize($test);

Posted: Mon Jun 05, 2006 9:15 pm
by bg
Funny. I read over the documentation 3 times and somehow managed to miss a return value. Damn you speed reading class, damn you.

Posted: Mon Jun 05, 2006 9:16 pm
by bdlang
bgzee wrote: Damn you speed reading class, damn you.
:D