Saving Objects

Previously, we covered how to save arrays in PHP using serialize(), unserialize(), urlencode(), and urldecode(). Saving objects works in the same way—you serialize() them into a string to make a format that can be saved, then urlencode() them to get a format that can be passed across the web without problem.

For example:

    $poppy = new Poodle('Poppy');
    $safepoppy = urlencode(serialize($poppy));

There is one special feature with saving objects: when serialize() and unserialize() are called, they will look for a _ _sleep() and _ _wakeup() method on the object they are working with, respectively. These methods, which you have to provide yourself if you want them to do anything, allow you to keep an object intact during its hibernation period (when it is just a string of data).

For example, when _ _sleep() is called, a logging object should save and close the file it was writing to, and when _ _wakeup() is called, the object should reopen the file and carry on writing. Although _ _wakeup() need not return any value, _ _sleep() must return an array of the values you wish to have saved. If no _ _sleep() method is present, PHP will automatically save all properties, but you can mimic this behavior in code by using the get_object_vars() method—more on that soon.

In code, our logger example would look like this:

 class Logger { private function _ _sleep() { $this->saveAndExit(); // return an empty array return array(); } private function _ _wakeup() { $this->openAndStart(); ...

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.