HomePHP Page 3 - The Basics of Serializing Objects in PHP
Creating self-serializing objects - PHP
Object serialization in PHP is very easy, and can be used for a variety of different purposes. It can be used to perform some fairly complex operations, in fact. This article, the first of a three-part series, introduces you to object serialization and a number of the tasks for which you can put this approach to use.
Having demonstrated how an object can be serialized from outside, the next step consists of showing how to create objects that are capable of serializing themselves. Sounds a little bit confusing? It isn't. Study the following class based on the previous example, which has the ability to serialize itself:
class DataSaver{ var $data; var $fileDir; function DataSaver($data){ if(!is_string($data)){ trigger_error('Invalid data type',E_USER_ERROR); } $this->data=$data; $this->fileDir='defaultDir'; } // save data to file function save(){ if(!$fp=fopen($this->fileDir.'/data.txt','w')){ trigger_error('Error opening data file',E_USER_ERROR); } fwrite($fp,$this->data); fclose($fp); } // fetch data from file function fetch(){ if(!$contents=file_get_contents($this- >fileDir.'/data.txt')){ trigger_error('Error opening data file',E_USER_ERROR); } return $contents; } function saveSerialized(){ if(!$fp=fopen($this->fileDir.'/data.txt','w')){ trigger_error('Error opening data file',E_USER_ERROR); } fwrite($fp,serialize($this)); fclose($fp); } }
As shown above, now the “DataSaver” class has an additional method, aside from the ones you saw in the previous example. In this case, the “saveSerialized()” method takes up the object itself, then serializes it and finally saves it to the specified text file. Quite interesting, right?
An example that covers how to use this self-serializing feature is illustrated by the snippet below:
// instantiate 'datasaver' object $dataSaver=&new DataSaver('This string will be saved to file'); // save data to file $dataSaver->save(); // save serialized object to file $dataSaver->saveSerialized();
With reference to the capacity offered by the “saveSerialized()” method, all the objects that have the capability to serialize themselves are commonly called self-serializing objects, and generally are used as base objects for deriving other objects that persist during the execution of an application. But in fact, I’m getting ahead of myself. Read the next section of the article, where I’ll explain how to create objects that are capable of performing a serialization/unserialization sequence on themselves.