PHP Destruct Magic Method

Posted on

What does it do?

The destruct function is called when the following occurrs;

  • Whenever a class is deleted
  • When the object falls out of scope
  • When the script ends

Why would you use it?

If you are removing a class from code and you no longer require its functionality it would be best to tie up all your loose ends. For example you may have a class that opens a stream, if there is life yet to to be lived in the script, make it more efficient by closing the file stream in the destruct method.

Example

class User {

    private $this->name;
    private $this->age;
    private $usersFile;

    public function getUsersFileStream()
    {
        return $this->usersFile = open('file/location/' . $this->getUserName(), 'r');
    }

    public function destruct()
     {
        //Uh oh the class if getting removed do clean up functionality here
        //Save the model to the database — in case it has changed and you may want to save it     
        // close the stream you have open to the users file —if the script is long running you may want to save resources
        fclose($this->usersFile);
      }
}