Serialization of data in PHP

Nov 28, 2010 Author: LinuxAdmin

Serialization of data means converting it into a string of bytes in such a way that you can produce the original data again from the string (via a process known, unsurprisingly, as unserialization). After you have the ability to serialize/unserialize, you can store your serialized string pretty much anywhere (a system file, a database, and so on) and recreate a copy of the data again when needed.

PHP offers two functions, serialize() and unserialize(), which take a value of any type (except type resource) and encode the value into string form and decode again, respectively. The PHP3 implementation of object serialization wasn’t very useful because member function definitions didn’t survive the serialization/unserialization process; beginning with version 4, however, PHP robustly recreates all important aspects of the instance from the string, as long as the class definition is available to the code where unserialize() is called.

Here is a quick example, which we’ll extend later in this section:

class ClassToSerialize {
public $storedStatement = “data”;
public function __construct($statement) {
$this->storedStatement = $statement;
}
public function display ()
{
print($this->storedStatement . “
”); } } $instance1 = new ClassToSerialize(“You’re objectifying me!”); $serialization = serialize($instance1); $instance2 = unserialize($serialization); $instance2->display();

This class has just one member variable and a couple of member functions, but it’s sufficient to demonstrate that both member variables and member functions can survive serialization. We create an object, convert it to a serialized string, convert it back to a new instance, and the printed result is the accurate complaint (You’re objectifying me!).

Of course, there is no point in serializing and unserializing an object in the same script. Serialization is only worthwhile when we expect the serialized string to outlive the script (and the variable) that it currently lives in and be reincarnated in another execution. This may be because we store the serialization in a file or a database and read it back in again. It can also happen automatically as a result of PHP’s session mechanism — variables that are registered as belonging to a session will be serialized and unserialized from page to page.


views 4041
  1. Add New Comment