Serialization and UnSerialization in PHP
Posted by Raj
Serialization/UnSerialization:
- Generates a storable representation of a value.
- serialize() returns a string containing a byte-stream representation of any value that can be stored in PHP.
- unserialize() can use this string to recreate the original variable values.
- This process makes a storable representation of a value that is useful for storing or passing PHP values.
- To make the serialized string into a PHP value again, use unserialize().
Before starting your serialization process, PHP will execute the __sleep function automatically. This is a magic function or method.
Before starting your unserialization process, PHP will execute the __wakeup function automatically. This is a magic function or method.
What can you Serialize and Unserialize?
- Variables
- Arrays
- Objects
- Resource-type
//BaseClass.php
<?php
class BaseClass {
public $var = 100;
public function show() {
echo $this->var;
}
}
// test1.php:
include("BaseClass.php");
$a = new A;
$v = serialize($a);
file_put_contents('store_in_var', $v);
// page2.php:
include("BaseClass.php");
$v = file_get_contents('store_in_var');
$a = unserialize($v);
$a->show();
?>
In the Case if you want to store entire array into database then with serialze() it would be useful to store an entire array in a field in a database.
You can pass an array to the function, and it will return a string that is essentially the string.
You can then unserialize() it to obtain the full array once again.
example:
<?php
$str_array = array( "Rajesh Sharma", "Rajesh", "RajeshS" );
$serialized_str = serialize($str_array);
echo $serialized_str;
?>
This will output a:3:{i:0;s:14:"Rajesh Sharma";i:1;s:6:"Rajesh";i:2;s:7:"RajeshS";}
so you can store entire array in a field in a database.
<?php
$str_array = array( "Rajesh Sharma", "Rajesh", "RajeshS" );
$serialized_str = serialize($str_array);
print_r(unserialize($serialized_str));
?>
This will output a Array ( [0] => Rajesh Sharma[1] => Rajesh [2] => RajeshS ).
$str_array = array( "Rajesh Sharma", "Rajesh", "RajeshS" );
$serialized_str = serialize($str_array);
print_r(unserialize($serialized_str));
?>
This will output a Array ( [0] => Rajesh Sharma[1] => Rajesh [2] => RajeshS ).
This entry was posted on October 4, 2009 at 12:14 pm, and is filed under
oop,
OOP interview questions and answers,
PHP,
PHP interview questions and answers,
Serialization,
unserialize
.You can leave a response, or trackback from your own site.