Serializing an object means converting it to a bytestream
representation that can be stored in a file. This is useful for persistent
data; for example, PHP sessions automatically save and restore objects.
Serialization in PHP is mostly automatic—it requires little extra work
from you, beyond calling the
$encoded = serialize(
something); $something = unserialize(
Serialization is most commonly used with PHP’s sessions, which
handle the serialization for you. All you need to do is tell PHP which
variables to keep track of, and they’re automatically preserved between
visits to pages on your site. However, sessions are not the only use of
serialization—if you want to implement your own form of persistent
unserialize() are a natural choice.
An object’s class must be defined before unserialization can occur.
Attempting to unserialize an object whose class is not yet defined puts
the object into
stdClass, which renders
it almost useless. One practical consequence of this is that if you use
PHP sessions to automatically serialize and unserialize objects, you must
include the file containing the object’s class definition in every page on
your site. For example, your pages might start like this:
// load object definitions
// load persistent variables
PHP has two hooks for objects during the serialization and