Destruct


computer apg

All objects can have a special built-in method called a constructor that allow we to initialize the object's properties whem we instantiate an object.



 __destruct 


The destruct method name, (function), is called when the object is destructed or the script is stopped or exited.

The destruct function starts with two underscores and ends with the word destruct.

If we create a __destruct function, PHP will automatically call this function at the end of the script.

In the next exercise, we find that by using the __construct function we save coding because such a function allows no set_... functions to be used, and a __destruct function that is automatically called at the end of the script:



  1 EXERCISE   

<?php

class Dwarf {
  public 
$name;
  public 
$behavior;

  function 
__construct($name$behavior) {
    
$this->name $name;
    
$this->behavior $behavior;
  }
  function 
__destruct() 
  {
    
    echo 
"The Dwarf is:<br> {$this->name} <br>and his behavior is:<br> {$this->behavior}<br><br>";
    
    echo 
'The class ' __CLASS__ ' is now destructed.<br>';
  }
}
$nm 'Happy';
$bh 'This dwarf is always cheerful and happy about everything.';

$apple = new Dwarf($nm$bh);

?>

 RESULT   

The Dwarf is:
Happy

and his behavior is:
This dwarf is always cheerful and happy about everything.


The class Dwarf is now destructed.