Serialize and Unserialize Object in PHP with Example

The below shows you how to serialize and unserialize a PHP object.

 

1. Serialize PHP Object

Use serialize() function to serialize an object.

example1.php
<?php

// create a new object
class Student {
	public $name;
	public $age;
	public $gender;
}
$student = new Student();
$student->name = 'Maria';
$student->age = '18';
$student->gender = 'female';

// convert the object to JSON string
$serializedString = serialize($student);

echo $serializedString;

Result:

O:7:"Student":3:{s:4:"name";s:5:"Maria";s:3:"age";s:2:"18";s:6:"gender";s:6:"female";}

 

2. Deserialize a serialized string

Use unserialize() function to deserialize a serialized string.

example2.php
<?php

// serialized string
$serializedString = 'O:7:"Student":3:{s:4:"name";s:5:"Maria";s:3:"age";s:2:"18";s:6:"gender";s:6:"female";}';

// deserialize the serialized string
$object = unserialize($serializedString);

var_dump($object);

Object:

object(__PHP_Incomplete_Class)#1 (4) {
  ["__PHP_Incomplete_Class_Name"]=>
  string(7) "Student"
  ["name"]=>
  string(5) "Maria"
  ["age"]=>
  string(2) "18"
  ["gender"]=>
  string(6) "female"
}

Leave a Reply

avatar