#native_company# #native_desc#
#native_cta#

The New PHP 5 Features for Constructors and Destructors

By Octavia Andreea Anghel
on December 21, 2010

As you probably know, the new OOP features in PHP 5 bring a new perspective to PHP applications. In this article, you will see the new PHP 5 features regarding constructors and destructors, which are one of the most important aspects in any type of object-orientated class. As a reminder, a constructor is a special function of a class that is automatically executed whenever an object of a class gets instantiated. A destructor is a special function of a class that is automatically executed whenever an object should be destroyed.
The article starts with a short overview of PHP 5 constructors, compared with the old fashion PHP 4. It continues with an explanation of writing constructors with or without parameters, restrictive constructors, overloading and PHP 5 destructors. At the end, you will be able to write almost any kind of constructor for your PHP 5 classes.

PHP 5 vs. PHP 4 Constructors

As a developer, each time you try to learn something new (a technology, a design pattern, a paradigm, etc.) you start by looking at what you used in the past and trying to identify the advantages of the new concept. This approach can tell you if using PHP 5 constructors is worth your time. To that end, consider the following comparison that explores why PHP 5 constructors are superior to PHP 4:
  • PHP 5 introduces new unified constructor/destructor names. In PHP 4, a constructor was just a method that had the same name as the class itself; this is a common approach in many programming languages. The main issue here is that each time you rename the class you must rename the constructor also.
  • In PHP 5, all constructors are named __construct() (that is, the word construct prefixed by two underscores).
  • PHP 5 introduces newly __destruct(), which is destruct prefixed by two underscores. This allows you to write code that will be executed when the object is destroyed and it is automatically called; parent destructors will not be called implicitly by the engine and it must explicitly call parent::__destruct() in the destructor body.
  • For backwards compatibility, if PHP 5 cannot find a __construct() function for a given class, it will search for the old-style constructor function by the name of the class, starting with PHP 5.3.3. Methods with the same name as the last element of a namespaced class name will no longer be treated as constructors.
Here are some important notes regarding constructors and destructors from the PHP documentation:
  • Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required.
  • Destructors called during the script shutdown have HTTP headers already sent. The working directory in the script shutdown phase can be different with some SAPIs (e.g. Apache).
  • Attempting to throw an exception from a destructor (called in the time of script termination) causes a fatal error.
  • A destructor cannot take any arguments.

Your First PHP 5 Constructor

Let’s start with a basic example of a PHP 5 constructor with no arguments. Its job will be to create an instance of its class and to initialize a set of class properties. Look through the code to get a first impression of what is happening.

<?php
class Player {
private $name;
private $surname;
private $country;
private $atp;
//this is a simple PHP 5 constructor
public function __construct() {
$this->name = "empty";
$this->surname = "empty";
$this->country = "empty";
$this->atp = 0;
}
public function setDetails($name, $surname, $country, $atp) {
$this->name = $name;
$this->surname = $surname;
$this->country = $country;
$this->atp = $atp;
}
public function displayDetails() {
echo "Name : " . $this->name . " Surname: " .
$this->surname . " Country: " . $this->country .
" Atp Ranking: " . $this->atp . "<br />";
}
}
$player_1 = new Player();
$player_1->displayDetails();
$player_1->setDetails("Rafael", "Nadal", "ESP", 1);
$player_1->displayDetails();
?>

The bolded code represents the PHP 5 unified constructor. The constructor’s body initializes the four class properties with default values, while the desired values are passed to the setDetails function. Notice the use of the $this keyword to indicate that you will initialize the class properties, not local properties.
The output of this class is shown in Figure 1 below.



Click here for larger image


Figure 1. Output of Player Class (Constructor with No Arguments)

Writing a PHP 5 Constructor with Parameters

Usually, the desired values are set inside the constructor, which is much closer to the real cases. When you create a class instance, you also set the object’s properties. The code below is similar to the one above; the only difference being that you eliminate the setDetails method and pass its behavior to the unified constructor:

<?php
class Player {
private $name;
private $surname;
private $country;
private $atp;
//this is a constructor with parameters
public function __construct($name, $surname, $country, $atp) {
$this->name = $name;
$this->surname = $surname;
$this->country = $country;
$this->atp = $atp;
}
public function displayDetails() {
echo "Name : " . $this->name . " Surname: " .
$this->surname . " Country: " . $this->country .
" Atp Ranking: " . $this->atp . "<br />";
}
}
$player_1 = new Player("Rafael", "Nadal", "ESP", 1);
$player_1->displayDetails();
$player_2 = new Player("Roger", "Federer", "SUI", 2);
$player_2->displayDetails();
?>

This kind of constructor is the most common in real applications. It receives a set of parameters — which have the same names as the class properties — and uses the $this keyword to associate each class property to the proper parameter.
The output of this class is shown in Figure 2 below.



Click here for larger image


Figure 2. Output of Player Class (Constructor with Parameters)

Your First PHP 5 Destructor

If the constructor is responsible for creating objects, the destructor is responsible for destroying objects. The destructor provides an elegant way for accomplishing necessary cleanup operations such as unsetting internal class objects, closing database connections or socket connections, etc. The destructor is automatically called when an object should be destroyed. An object of a class is destroyed when:
  • it goes out of scope
  • you specifically set it to null
  • you unset it or the program execution is over
The destructor below calls the unset method with the class property passed as an argument:

<?php
class Player {
private $name;
private $surname;
private $country;
private $atp;
public function __construct($name, $surname, $country, $atp) {
$this->name = $name;
$this->surname = $surname;
$this->country = $country;
$this->atp = $atp;
}
public function displayDetails() {
echo "Name : " . $this->name . " Surname: " . $this->surname . "
Country: " . $this->country . " Atp Ranking: " . $this->atp . "<br />";
}
public function __destruct() {
unset($this->name);
unset($this->surname);
unset($this->country);
unset($this->atp);
echo("
Object destroyed ...");
} } $player_1 = new Player("Rafael", "Nadal", "ESP", 1); $player_1->displayDetails(); $player_2 = new Player("Roger", "Federer", "SUI", 2); $player_2->displayDetails(); ?>

The output of this class is shown in Figure 3 below.



Click here for larger image


Figure 3. Output of Player Class (Destructor)
Here are some important notes regarding destructors from the PHP documentation:
  • Attempting to throw an exception from a destructor (called in the time of script termination) causes a fatal error.
  • A destructor cannot take any arguments.