OOP PHP Lesson 3 – Constructor and Destructor

a metal screw - illustration for php oop lesson 3 basics

Usually – in most languages – constructor is a function which has the same name as class name. It was so in PHP v. 5.3.0 up to 5.3.2 but starting from PHP version 5.3.3 such function with class name is treated like a regular function. This information is important for backward compatibility if PHP version installed on your server is earlier than 5.3.3.

Constructor method is called by class every time when object is created – it is impossible to call earlier any other class method – so this is a good place to initialize some properties of object before we can use it. Destructor is called every time object is destroyed, and this is the last called class method. Destructor method is very suitable place for code aimed to free resources (write data to database, close database connections etc).

In this lesson we use PHP code from lesson 2, but modified as is shown below:

class Customer {

function __construct() {

   $this->name="John";
   echo 'Hello from constructor! Customer name is created.<br />';

}

function __destruct() {

   echo 'object destroyed!<br />';
   //some management - free resources here to avoid leak

}

private $name="";

public function set_name($a_name) {
   if($this->name=="") {
      $this->name = $a_name;
   } else {

          echo 'Customer is already named: '.$this->name.'<br />';
   }
}

public function get_name() {

   echo $this->name.'<br />';

}

public function say_hello() {

   if($this->name!="") {

   echo 'Customer '.$this->name.' says: Hello!<br />';

  } else {

  echo 'Please give name to your new customer (there is nobody to say Hello!)<br />';

      }
}

}

Constructor method __construct is place where we set customer name via access to private $name. From output results we can see that it is impossible to change the name – as expected, because it was set at the time object was created. There is no need to call constructor or destructor explicitly, and actually calling both constructor and destructor explicitly throws an error. unset() is used to delete object (and free memory). Destructor method is extremely important if object uses resources which – after deleting object – could be not freed and for this reason all “closing resources” management should be placed in destructor. Maybe resources will be freed later anyway, due to closing web page or for other reasons, but it is good programming habit to free resources if object you created has been deleted and didn’t use them anymore.

Class code for example with constructor and destructor:

require('Customer.php');

$a_customer = new Customer();
$a_customer->set_name("Steven");
$a_customer->get_name();
$a_customer->say_hello();

unset($a_customer);

And output for the above code:

Hello from constructor! Customer name is created.
Customer is already named: John
John
Customer John says: Hello!
object destroyed!