problem with serialize and magic method __sleep()

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
bg
Forum Contributor
Posts: 157
Joined: Fri Sep 12, 2003 11:01 am

problem with serialize and magic method __sleep()

Post 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:"
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

your implementation of __sleep doesn't return data to be serialized.
bdlang
Forum Contributor
Posts: 395
Joined: Tue May 16, 2006 8:46 pm
Location: Ventura, CA US

Post 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);
bg
Forum Contributor
Posts: 157
Joined: Fri Sep 12, 2003 11:01 am

Post 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.
bdlang
Forum Contributor
Posts: 395
Joined: Tue May 16, 2006 8:46 pm
Location: Ventura, CA US

Post by bdlang »

bgzee wrote: Damn you speed reading class, damn you.
:D
Post Reply