Home arrow PHP arrow Page 2 - The Basics of Serializing Objects in PHP

Explaining the core concepts - 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.

TABLE OF CONTENTS:
  1. The Basics of Serializing Objects in PHP
  2. Explaining the core concepts
  3. Creating self-serializing objects
  4. Creating self-saving objects
By: Alejandro Gervasio
Rating: starstarstarstarstar / 46
June 06, 2006

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

In order to illustrate how an object, that is converted to a byte-stream representation of its methods and properties, can be serialized, I’ll set up a concrete example that will show the complete sequence for serializing/unserializing the object in question.

Of course, before any attempt is made to serialize an object, I should define a class from which I can create different instances. Thus, here is a sample PHP class named “DataSaver,” which is simply tasked with saving an input string to a given text file. This class looks like this:

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;
    }
}

In this case, the class listed above accepts as an incoming argument a string, which can be saved to a specific file and then retrieved at a later time, by using the “save()” and “fetch()” methods respectively. Now, pay attention to the following snippet, where an instance of the “DataSaver” class is serialized, and in turn restored to its original state:

// instantiate 'datasaver' object
$dataSaver=&new DataSaver('This string will be saved to file');
// save data to file
$dataSaver->save();
// display sample data
echo $dataSaver->fetch().'<br />';
// serialize object
$dataObj=serialize($dataSaver);
$dataObj=unserialize($dataObj);
// call object methods after unserializing object
echo $dataObj->fetch();

As you can see, the above example shows a few interesting things. Notice how after instantiating a "DataSaver" object, and calling its “save()” and fetch()” methods, this object is serialized and next unserialized through the corresponding “serialize()/unserialize()” functions.

Of course, the most important thing regarding the previous example consists of emphasizing how the object can be restored to its original state, which means that all its methods can be called as expected. The following lines clearly illustrate this concept:

// serialize object
$dataObj=serialize($dataSaver);
$dataObj=unserialize($dataObj);
// call object methods after unserializing object
echo $dataObj->fetch();

The output of the above snippet is as follows:


This string will be saved to file

Certainly, the above example demonstrates the ease, offered by PHP, of serializing an object inside an application, as well as reversing the process and using the object’s methods and properties accordingly. This concept can be potentially very handy, particularly in situations where you need to save your objects at least temporally, and then retrieve them at a later time.

After showing the first example of how to serialize/unserialize an object, I hope you understand how the whole process works, as well as the possible implementations of this technique inside an application.

Now, it’s time to learn how to use serialization inside of objects, thus in order to learn more about this approach, please click on the link below.



 
 
>>> More PHP Articles          >>> More By Alejandro Gervasio
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: