Friday, June 5, 2009

serialize, unserialize, __sleep() and wakeup()

definitions:

Serialization: convert an object into a string (storable representation). The included object (instantiated and assigned to internal members) are included in the string.
Unserialization: convert the string into the original object

Possibile uses: shopping cart serialize (to use after or to save into a db), user session save, object transfer between different applications.

serialize($anyContent)
returns a storable representation of $anyContent

example:
serialize(array("val",array(1,2))); //= a:2:{i:0;s:3:"val";i:1;a:2:{i:0;i:1;i:1;i:2;}

unserialize($serializedString)
returns a php value of a serialized string (made using serialize())
$obj = unserialize(a:2:{i:0;s:3:"val";i:1;a:2:{i:0;i:1;i:1;i:2;});
print_r( $obj );
//Array ([0] => val [1] => Array([0] => 1 [1] => 2 ))

to be more clearly
unserialize(serialize($anyContent))
it's equal to
$anyContent

when is the serialization useful ? some example:
  • $_SESSION
  • db connection handlers
  • in general: save object content
PHP5 offers magic methods to serialize and unserialize objects

__sleep() and __wakeup()
Considering the object $classObject:
  • __sleep() is automatically called before serialize($classObject) is invoked.
    It returns an array contains the name of the members to serialize.
    Note: the behavior indicated in the official php documentation is different from the result I've obtained in php 5.2.8: every member is serialized, the returning array is ignored !
  • __wakeup() is automatically called when we invoke unserialize($classObject)
    It should return and object

class Product
{
public
$name;
public
$quantity;
public function
__construct($name, $quantity) {
$this->name = $name;
$this->quantity = $quantity;
}
}

class
ShopCart
{
private
$userID = "abc123";
public
$products = array( );
public function
__construct()
{
//insert some default products
$this->products[0] = new Product("pencil", 3);
$this->products[1] = new Product("pen", 5);
}

public function
__sleep()
{
//no userID returned
return array("products");
}
}

$s = new ShopCart();
//print $s->products[1]->quantity."\n"; //5
$s2 = unserialize(serialize($s));

var_dump($s2);
/*
object(ShopCart)#4 (2) {
["userID:private"]=>
string(6) "abc123" // ???????????????????
["products"]=>
array(2) {
[0]=>
object(Product)#5 (2) {
["name"]=>
string(6) "pencil"
["quantity"]=>
int(3)
}
[1]=>
object(Product)#6 (2) {
["name"]=>
string(3) "pen" // ???????????????????
["quantity"]=>
int(5)
}
}
}
*/

No comments:

Post a Comment

 

PHP and tips|PHP