PHP serialize / unserialize

May 16th, 2010 by Alex Leave a reply »

PHP is so huge, that you find new and new functions every day. The life is so strange, that i didn’t use serialize functions anywhere, and now the time has come.

What is serialize used for? Let me give you an example. Let’s imagine we have an object and it has 2 or 5 or 10 options, like this:

class Object {
	public function Object() {
	}
}
 
$o = new Object();
$o->options = array("scale"=>"no", "size"=>5, "has_options"=>"yes", "available"=>"yes");

Now, let’s save this object to MySQL.. Create a table named Objects with fields “scale”, “size”, “has_options”, “available”? No way! Especially when we’ll have like 100 properties, we may experience huge mysql table size increase. Let’s see what our serialize makes.

$s = serialize($o);
echo $s;

Our script should echo the next string:

O:6:"Object":1:{s:7:"options";a:4:{s:5:"scale";s:2:"no";s:4:"size";i:5;s:11:"has_options";s:3:"yes";s:9:"available";s:3:"yes";}}

Now, you may see that O means Object, S means String, I means Integer and so on. The string is much less than 255 symbols, so we can easily store it in single mysql field. Now, when we get this field from the database, all we have to do is unserialize the field and use the object as we used it before:

$o = unserialize($string_to_unserialize);
print_r($o->options);

And here we have the options array as we had it before:

Array (
  [scale] => no
  [size] => 5
  [has_options] => yes
  [available] => yes
)

Comments are closed.