The __sleep Method

The __sleep method is automatically called when serializing an object using the serialize function. This method should return an array of property names that should be included in the serialized representation of the object.

Syntax

phppublic function __sleep(): array;

Example

Let's create a class and implement the __sleep method to serialize only specific properties:

php<?php
class User {
  public $name = 'John';
  public $age = 30;
  private $password = '12345';
  
  public function __sleep() {
    return ['name', 'age'];
  }
}

$user = new User();
echo serialize($user);
?>

Code execution result:

php'O:4:"User":2:{s:4:"name";s:4:"John";s:3:"age";i:30;}'

Example

Using __sleep to exclude confidential data from serialization:

php<?php
class Account {
  public $login = 'admin';
  private $password = 'secret';
  public $email = 'admin@example.com';
  
  public function __sleep() {
    return ['login', 'email'];
  }
}

$account = new Account();
echo serialize($account);
?>

Code execution result:

php'O:7:"Account":2:{s:5:"login";s:5:"admin";s:5:"email";s:17:"admin@example.com";}'

See Also

  • the __wakeup method,
    which is called during object deserialization
  • the serialize function,
    which serializes data