PHP serialize

Summary: in this tutorial, you’ll learn how to the PHP serialize() function to serialize an object.

Introduction to the PHP serialize() function

To serialize an object into a string, you use the serialize() function:

serialize(mixed $value): stringCode language: PHP (php)

The serialize() function returns a string that contains a byte-stream representation of the object. And you can store this string in storage such as a file or a database.

For example, the following defines the Customer class:

<?php

class Customer
{

    private $id;

    private $name;

    private $email;

    public function __construct(int $id, string $name, string $email)
    {
        $this->id = $id;
        $this->name = $name;
        $this->email = $email;
    }

    public function getInitial()
    {
        if ($this->name !== '') {
            return strtoupper(substr($this->name, 0, 1));
        }
    }
}Code language: PHP (php)

And this illustrates how to use the serialize() function to serialize a Customer object:

<?php

require 'Customer.php';

$customer = new Customer(10, 'John Doe', '[email protected]');
$str = serialize($customer);

var_dump($str);Code language: PHP (php)

Output:

string(132) "O:8:"Customer":3:{s:12:"Customerid";i:10;s:14:"Customername";s:8:"John Doe";s:15:"Customeremail";s:20:"[email protected]";}"Code language: PHP (php)

Notice that the serialize() function only serializes the properties of the object, not the method.

The following example serializes a Customer object and saves the string to a file:

<?php

require 'Customer.php';

$customer = new Customer(10, 'John Doe', '[email protected]');
$str = serialize($customer);

file_put_contents('customer.dat', $str);Code language: PHP (php)

The __sleep() magic method

The serialize() function checks if the class implements the __sleep() method. If so, it’ll execute the __sleep() method before serializing the object.

public __sleep(): arrayCode language: PHP (php)

The __sleep() method returns an array that contains property names that will be serialized.

If the __sleep() method doesn’t return anything, the serialize() function will serialize null value and issue an E_NOTICE.

The following example illustrates how to implement the __sleep() method:

<?php

class Customer
{
    private $id;
    private $name;
    private $email;

    public function __construct(int $id, string $name, string $email)
    {
        $this->id = $id;
        $this->name = $name;
        $this->email = $email;
    }

    public function getInitial()
    {
        if ($this->name !== '') {
            return strtoupper(substr($this->name, 0, 1));
        }
    }

    public function __sleep(): array
    {
        return ['id', 'name'];
    }
}Code language: PHP (php)

In this example, the __sleep() method returns an array that contains the names of the id and name properties. And the serialize() function will only serialize the values of these properties:

<?php

require 'Customer.php';

$customer = new Customer(10, 'John Doe', '[email protected]');
$str = serialize($customer);

var_dump($str);Code language: PHP (php)

Output:

string(81) "O:8:"Customer":2:{s:12:"Customerid";i:10;s:14:"Customername";s:8:"John Doe";}"Code language: PHP (php)

In practice, you would want to encrypt sensitive information such as email and credit card numbers before carrying the serialization.

The __serialize() magic method

The __serialize() method is similar to the __sleep() method:

public __serialize(): arrayCode language: PHP (php)

However, the __serialize() method returns an associative array of key/value pairs representing the object’s serialized form.

Also, if the __serialize() method doesn’t return an array, PHP will throw a TypeError.

For example:

<?php

class Customer
{
    private $id;

    private $name;

    private $email;

    public function __construct(int $id, string $name, string $email)
    {
        $this->id = $id;
        $this->name = $name;
        $this->email = $email;
    }

    public function getInitial()
    {
        if ($this->name !== '') {
            return strtoupper(substr($this->name, 0, 1));
        }
    }

    public function __serialize(): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
        ];
    }
}Code language: PHP (php)

The following illustrates how to use the serialize() function to serialize a Customer object:

<?php

require 'Customer.php';

$customer = new Customer(10, 'John Doe', '[email protected]');
$str = serialize($customer);

var_dump($str);Code language: PHP (php)

If a class has both __serialize() and __sleep() method, the serialize() function calls the __serialize() method only and ignores the __sleep() method.

Summary

  • Use the serialize() function to serialize an object into a string of byte-stream representation.
  • Use the __sleep() or __serialize() method to implement the logic before serialization.
Did you find this tutorial useful?