05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>PHP</strong> has two hooks for objects during the serialization and unserialization process:<br />

_ _sleep( ) and _ _wakeup( ). These methods are used to notifyobjects that they’re<br />

being serialized or unserialized. Objects can be serialized if theydo not have these<br />

methods; however, they won’t be notified about the process.<br />

The _ _sleep( ) method is called on an object just before serialization; it can perform<br />

anycleanup necessaryto preserve the object’s state, such as closing database connections,<br />

writing out unsaved persistent data, and so on. It should return an arraycontaining<br />

the names of the data members that need be written into the bytestream. If<br />

you return an empty array, no data is written.<br />

Conversely, the _ _wakeup( ) method is called on an object immediatelyafter an<br />

object is created from a bytestream. The method can take any action it requires, such<br />

as reopening database connections and other initialization tasks.<br />

Example 6-3 is an object class, Log, which provides two useful methods: write( ) to<br />

append a message to the logfile, and read( ) to fetch the current contents of the logfile.<br />

It uses _ _wakeup( ) to reopen the logfile and _ _sleep( ) to close the logfile.<br />

Example 6-3. The Log.inc file<br />

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!