← Back to Chapters

PHP OOP __sleep() Method

? PHP OOP __sleep() Method

? Quick Overview

The __sleep() magic method is automatically triggered when an object is serialized using serialize(). It allows developers to control which object properties are stored.

? Key Concepts

  • Controls object serialization behavior
  • Returns an array of property names
  • Skips non-serializable resources
  • Works together with __wakeup()

? Syntax & Theory

The __sleep() method is useful when objects contain resources like database connections that should not be serialized.

? View Code Example
// Demonstrates how __sleep controls object serialization
<?php
class User {
public $name;
public $email;
private $dbConnection;

public function __construct($name, $email) {
$this->name = $name;
$this->email = $email;
$this->dbConnection = "DB Connection Resource";
}

public function __sleep() {
// Only serialize safe properties
return ['name', 'email'];
}
}

$user = new User("Meghraj", "meghraj@example.com");
$serializedUser = serialize($user);
echo $serializedUser;
?>

? Output Explanation

The serialized string includes only name and email. The database connection is excluded, preventing errors and reducing data size.

? Use Cases

  • Storing objects in sessions
  • Caching object state
  • Preparing objects for network transfer
  • Preventing serialization of resources

✅ Tips & Best Practices

  • Serialize only necessary properties
  • Always pair with __wakeup() if resources need restoration
  • Use for session-safe and cache-safe objects

? Try It Yourself

  • Create a Session class with userId, token, and dbHandle
  • Implement __sleep() to serialize only safe properties
  • Serialize and print the object
  • Optionally restore the resource using __wakeup()