Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

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(); } private ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page