PHP Serializable interface

PHPServer Side ProgrammingProgramming


The Serializable interface is present in PHP library to build a class that provides custimised serialzing. PHP's serialize() function is able to serialize most of the values to a storable representation. However, objects of user defined classes can not be serialized. This interface makes it possible.


Serializable {
   /* Methods */
   abstract public serialize ( void ) : string
   abstract public unserialize ( string $serialized ) : void


Serializable::serialize — String representation of object

Serializable::unserialize — Constructs the object from serialized string representation

The built-in serialze() function Generates a storable representation of a value

serialize ( mixed $value ) : string

unserialize() function Creates a PHP value from a stored representation

unserialize ( string $str [, array $options ] ) : mixed

Serializable Example

In following example, a string variable is used private proprty of myclass. When built-in serialize() function uses object of this class as argument, serialize() method is automatically called. Similarly, unserialize() function reconstructs the object with string prvate property.


 Live Demo

class myclass implements Serializable {
   private $arr;
   public function __construct() {
      $this->arr = "TutorialsPoint India (p) Ltd";
   public function serialize() {
      echo "Serializing object..\n";
      return serialize($this->arr);
   public function unserialize($data) {
      echo "Unserializing object..\n";
      $this->arr = unserialize($data);
   public function getdata() {
      return $this->arr;
$obj = new myclass;
$serobj = serialize($obj);
var_dump ($serobj);
$obj1 = unserialize($serobj);


Above program shows following output

Serializing object..
string(55) "C:7:"myclass":36:{s:28:"TutorialsPoint India (p) Ltd";}"
Unserializing object..
string(28) "TutorialsPoint India (p) Ltd"
Published on 21-Sep-2020 15:21:42