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:

<?php
	include('person.inc');

	$sharon = new Person;
	$sharon->name = "Sharon";
	$serialSharon = serialize($sharon);
	file_put_contents('./file.txt', $serialSharon);

	echo "Sharon object has been stored in the 'file.txt' file.<br>";

	echo "Click <a href=\"read.php\">here</a> to go to the retrieving page that reads the Sharon object from 'file.txt'.<br>";

	echo "<pre>" . var_export($sharon, TRUE) . "</pre>" ;
?>

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

 

Next is the person.inc file:

<?php
	class Person {

		public $name;
		public $created;

		public function __construct(){
			$this->created = time();
			echo "Object instantiated at " . $this->created . "<br>";
		}
		public function display(){
			echo "Hi, my name is $this->name and I was created at $this->created.<br>";
		}
	}
?>

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:

<?php
	include('person.inc');

	echo "The Sharon object will now be read from 'file.txt'.<br>";

	$unserialSharon = file_get_contents('./file.txt');
	$readIn = unserialize($unserialSharon);

	$readIn->display();

	echo "<pre>" . var_export($readIn, TRUE) . "</pre>" ;
?>

*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