__sleep & __wakeup in PHP 5

-

Introduction

When you serialize and unserialize a PHP object, PHP will automatically check to see if there is a __sleep or __wakeup magic method in the class (depending on weather your serializing or unserializing).

Using __sleep

When you serialize an object, PHP automatically checks to see if the object has a __sleep magic method. The sleep method is used because you might not want to serialize the whole object, sometimes just a specific array for example.

The example below demonstrates a class that would use the __sleep method when serialized:

The above code will save a serialized version of the ‘info’ array in the variables ‘data’.

Using __wakeup

When you unserialize an object, PHP automatically checks to see if the object has a __wakeup magic method. The __wakeup method would usually be used to re-connect to the database and re-store any data that was not stored in the object when it was serialized back into the objects properties.

Comments

Visitor stats.