Questions And Answers

More Tutorials

PHP Object Serialization

Serialize / Unserialize

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.
To serialize an object


To Unserialize an object



$array = array();
$array["a"] = "Foo";
$array["b"] = "Bar";
$array["c"] = "Baz";
$array["d"] = "Wom";

$serializedArray = serialize($array);
echo $serializedArray;



The Serializable interface

Classes that implement this interface no longer support __sleep() and __wakeup(). The method serialize is called whenever an instance needs to be serialized. This does not invoke __destruct() or has any other side effect unless programmed inside the method. When the data is unserialized the class is known and the appropriate unserialize() method is called as a constructor instead of calling __construct(). If you need to execute the standard constructor you may do so in the method.

Basic usage

class obj implements Serializable {
 private $data;
 public function __construct() {
 $this->data = "My private data";
 public function serialize() {
 return serialize($this->data);
 public function unserialize($data) {
 $this->data = unserialize($data);
 public function getData() {
 return $this->data;

$obj = new obj;
$ser = serialize($obj);


string(38) "C:3:"obj":23:{s:15:"My private data";}"

$newobj = unserialize($ser);


string(15) "My private data"


In this page (written and validated by ) you learned about PHP Object Serialization . What's Next? If you are interested in completing PHP tutorial, your next topic will be learning about: PHP Reading raw POST data.

Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue:

Share On:

Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using, you agree to have read and accepted our terms of use, cookies and privacy policy.