Saving Objects - Serialization

To save objects the serialize() function is used to convert them into a format that can be saved, like so:

 

$target = serialize($source);

 

This can now be saved to a file using the file_put_contents() function, like so:

 

file_put_contents('path/file.txt', $target);

 

To read the object the complementary functions unserialize() and file_get_contents are utilised, like so:

 

$target = file_get_contents('path/file.txt'); //assigns the file contents

$source = unserialize($target); //converts back to the correct format

 

 

The following example is broken into 3 separate files. First we have the index.php file:

*note: the var_export() function is being used to show the contents of the object

 

Next is the person.inc file:

Save & refresh browser:

Object instantiated at 1372945579
Sharon object has been stored in the 'file.txt' file.
Click here to go to the retrieving page that reads the Sharon object from 'file.txt'. 

 

Person::__set_state(array(
'name' => 'Sharon',
'created' => 1372945579,
))

 

 

Finally, we have the read.php file:

*note: the var_export() function is being used to show the contents of the object

 

Save & refresh browser:

The Sharon object will now be read from 'file.txt'.
Hi, my name is Sharon and I was created at 1372945579. 

 

Person::__set_state(array(
'name' => 'Sharon',
'created' => 1372945579,
))

 

 

Note: static members of an object are not serialized

 

 

 

When saving and reading objects using serialize() and unserialize, they automatically look for __sleep() and __wakeup() magic methods for their respective function. You will need to provide these magic methods yourself and are used to perform cleanups of the object before being saved or read.

Leave a Reply