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:

Code:
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().

Code:
<?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..

Related Articles:

Follow me on Twitter!

Your Ad Here

One Response to “How-to: Use __sleep() to serialize your class”

  1. MC says:

    oh god thank you for this!!

Leave a Reply

Line and paragraph breaks automatic.
XHTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>