PHP Serializable interface

The Serializable interface in PHP allows custom classes to define their own serialization behavior. While PHP's built-in serialize() function can handle most data types, objects of user-defined classes need this interface to control how they are converted to and from string representations.

Syntax

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

Methods

Serializable::serialize() − Returns a string representation of the object

Serializable::unserialize() − Reconstructs the object from its serialized string representation

Built-in Functions

PHP provides built-in functions that work with the Serializable interface:

serialize() − Generates a storable representation of a value

serialize(mixed $value) : string

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

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

Example

Here's how to implement the Serializable interface in a custom class ?

<?php
class myclass implements Serializable {
    private $data;
    
    public function __construct() {
        $this->data = "TutorialsPoint India (p) Ltd";
    }
    
    public function serialize() {
        echo "Serializing object..<br>";
        return serialize($this->data);
    }
    
    public function unserialize($serialized) {
        echo "Unserializing object..<br>";
        $this->data = unserialize($serialized);
    }
    
    public function getData() {
        return $this->data;
    }
}

$obj = new myclass();
$serializedObj = serialize($obj);
var_dump($serializedObj);

$obj1 = unserialize($serializedObj);
var_dump($obj1->getData());
?>
Serializing object..
string(55) "C:7:"myclass":36:{s:28:"TutorialsPoint India (p) Ltd";}"
Unserializing object..
string(28) "TutorialsPoint India (p) Ltd"

How It Works

When serialize() is called on an object implementing Serializable, PHP automatically invokes the object's serialize() method. Similarly, when unserialize() processes the serialized string, it calls the object's unserialize() method to reconstruct the object.

Conclusion

The Serializable interface provides fine-grained control over object serialization in PHP. It's essential when you need to customize how objects are stored and retrieved, ensuring data integrity across serialization operations.

Updated on: 2026-03-15T09:25:00+05:30

708 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements