How-to: Use __sleep() to serialize your class
A lot of people run into this problem, and so did I when I first tried this. To make a long story short, I had a class which I wanted to serialize and store in a session variable. I would serialize the class, but when I would echo the output I’d get this:
N;
This would happen regardless of what was in the class. The class used a ‘magic’ function __sleep() to close the db connection. I had read that serialize() automatically calls __sleep(), but I didn’t know is that __sleep() needed to return an array of properties of the class.
Here is some example code to try out. Use it as is, and then comment out the contents in __sleep().
<?php
class sleep_example {
private $var1 = "george";
public function __construct() {}
public function __sleep() {
return array_keys(get_object_vars($this));
}
}
$obj1 = new sleep_example();
$srlz = serialize($obj1);
echo $srlz;
?>
Hopefully you’ll read this before you waste time googl’ing and looking through PHP Bug reports..


November 3rd, 2009 at 11:36 am
oh god thank you for this!!