PHP object destruct


Corresponding to the constructor method is the destructor method, destructor method allows the destruction of a class before the implementation of some operations or complete some functions, such as close the file, release the result set and so on. The destructor can not take any arguments, and its name must be __destruct().

grammar:

function __destruct()
{
    ...
}

In the above example, we add the following destructor method:

// Define a destructor method
function __destruct()
{
    echo "see ". $this->name;
}

Run the example again and output:

My name is David
The age is
Goodbye David

Tip

  1. As with the constructor, PHP does not automatically call the parent's destructor in this class. To execute the destructor method of the parent class, you must call parent::__destruct() manually in the destructor body of the subclass.
  2. Attempting to throw an exception in the destructor results in a fatal error.
  3. In PHP4 version, the name of the constructor must be the same as the class name, and there is no destructor.



Copyright 2014-2017 by DeveloperTut.com. All Rights Reserved.
TwitterGoogle+Facebook