PHP
  Home arrow PHP arrow Page 2 - The Basics of Serializing Objects in PHP
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PHP

The Basics of Serializing Objects in PHP
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 35
    2006-06-06


    Table of Contents:
  • The Basics of Serializing Objects in PHP
  • Explaining the core concepts
  • Creating self-serializing objects
  • Creating self-saving objects

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    The Basics of Serializing Objects in PHP - Explaining the core concepts
    ( Page 2 of 4 )

    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
     

       

    PHP ARTICLES

    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL
    - Method Chaining: Adding More Methods to the ...
    - Method Chaining in PHP 5
    - The Role of Interfaces in Applying the Depen...
    - Dependency Injection: Using a Setter Method ...
    - Using a Model Class with the Dependency Inje...
    - Injecting Objects Using Setter Methods with ...
    - Injecting Objects by Constructor with the De...
    - The Dependency Injection Design Pattern in P...
    - Performing Inferential Statistical Analysis ...
    - Performing Descriptive Statistical Analysis ...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 6 Hosted by Hostway
    Stay green...Green IT