Serializing Objects in PHP

Title :Serializing Objects in PHP
Full Article: http://www.phphacks.com/content/view/34/33/

Recommended to : Beginner PHPer and PHPer just starting OO

Introduction: Object serialization is a technique to turn an object's properties and methods into a string. It is then stored in flatfile or database. Unserialize them will turn the object into the original state and can be processed in PHP. This article from phphacks.com shows how to build a class that can self serialize and unserialize.

Abstract:
To serialize a object, use serialize($object). To unserialize, use unserialize($object). The writer demonstrate the usage by making a simple class that simply store data into file. Then, adding a new function in the original class that allow serialization the object itself by this code serialize($this). The serialized object is then stored into a file. Restoration of the file needs another function. The function called fetch() fetches the file and unserialize it. "$newObj = $objSaver-> fetch();" will create an object that's same as the $objSaver.

Facts from Conclusion:

  • Serialization turns a object into string for storage.
  • Unserialization restores a string into an object for PHP script to use.
  • Self-serializing and unserializing objects can be a root class for all classes that need to serialized.

Editor Comment:

Serialize is a practice quite popular around the OO PHPers. The popular CMS e107 uses Serialized object to store settings in the database.


Post new comment

The content of this field is kept private and will not be shown publicly.
If you have a Gravatar account, used to display your avatar.
  • Allowed HTML tags: <img> <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <span> <fn>
  • Lines and paragraphs break automatically.
  • Textual smileys will be replaced with graphical ones.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>. Beside the tag style "<foo>" it is also possible to use "[foo]".
  • Use [fn]...[/fn] (or <fn>...</fn>) to insert automatically numbered footnotes.

More information about formatting options

What is 23 + 16?
To combat spam, please solve the math question above.
Honey Pot that kill bots