__sleep() method

__sleep() is a magic method : it is called an object is being serialized, so that the object may be cleaned.

In particular, some resources, such as database connexions or files cannot be serialized. They should be closed, stored as a path, and reopened later with __wakeup().

The __sleep() method is usually paired with the __wakeup() method.

<?php

class x {
     private $file;
     private $path;

     function __sleep() {
             fclose($this->path);
     }

     function __wakeup() {
             $this->path = fopen($this->path, 'r');
     }
}

?>

Documentation

See also PHP __sleep And __wakeup Magic Methods: How And When To Use Them?, __sleep() and __wakeup()

Related : Magic Methods, __wakeup() method