Categories
PHP

Class Constructor and Destructor

When an instance of a class is created the PHP engine executes the constructor method that builds the object with any existing properties and methods. And when the object is no longer needed or the script is finished executing, the PHP engine executes the destructor method and removes the object from the system’s memory.

<?php
 class User {
  public $username = 'Guest';
  public function setUsername($u) {
   return $this->username = $u;
  }
 }

While I had the beginnings of a User object type earlier, one thing about its usage that certainly seems suboptimal is the need to set the member data manually. To use it, I would have to write code along the following lines:

<?php
 $user = new User();
 $user->setUsername = 'Admin';

Constructor

Constructor is a method that is executed whenever a new instance of the object type is created. The constructor can accept parameters that are passed via the call to the new operator by putting them in parentheses after the type name. If you do not write your own constructor, a default or blank one is provided for you that accepts no parameters.

Let’s define the constructor for the User class that accepts one parameter $u (username). To define a constructor, you define a function with the name __construct:

<?php
 class User {
  public $username = 'Guest';
  public function __construct($u) {
   $this->username = $u;
  }
 }

Now, when you create an instance of this class, you are obliged to pass in the required data (you no more need to define and use the $user->setUsername() method):

<?php
 $user = new User ('Admin');
 echo $user->username; # Admin

Notice the default value ‘Guest‘ for the $username property is useless as you’ve to provide the username whenever you create a new object. To solve this issue, you can assign the default value for the $username property in the __construct function, see the following code:

<?php
 class User {
  public $username;
  public function  __construct($u = 'Guest') {
   $this->username = $u;
  }
 }
 
 $user1 = new User();
 $user2 = new User('Admin');
 
 echo $user1->username; #Prints: Guest
 echo $user2->username; #Prints: Admin

Note: The constructor method is used exclusively for creating a new object, so it should not use return.

Destructure

The destructor is a method that is called automatically whenever an object is finally destroyed. To define a destructor, you define a function with the name __destruct, unlike the __construct method, it does not accept any parameter:

<?php
 class User {
  public $username = 'Guest';
  public public __construct($u) {
   $this->username = $u;
  }

  public public __destruct() {
   // put any cleanup code here!!
  }
 }

Note: The destructor for an object instance is not always called when you would expect. If PHP can easily determine there are no outstanding references left to an object, it immediately destroys the object and calls your destructor. However, in other situations, it may take until the end of the script to figure out that there are no references to an object that can be destroyed.

Example: Creating a basic website template with class constructor and destructor:

The template.php file act as a website template, it uses just two methods __construct and __descrutct. The constructor will print the necessary HTML code for the page header and the page title, and the destructor prints the HTML code for the page footer:

<?php
 # template.php
 class Template {
  public function __construct($title) {
?>
<html><head><title><?=$title?></title></head><body>
<?php
  }

  public function __destruct() {
?>
<p style="padding:10px;color:#fff;background:#000">
   Page Footer &copy;2022
</p></body></html>
<?php
  }
 }

To use the above template, include the template file, then create an instance of Template class, write your page content and upload or save the file in your web directory:

<?php
 # example.php
 require 'template.php'
 $t = new Template('The Page Title');

?>
<h1>OOP Tutorial</h1>
<p style="padding:10px">The destructor for an object instance is not always called when you would expect. If PHP can easily determine there are no outstanding references left to an object, it immediately destroys the object and calls your destructor. However, in other situations, it may take until the end of the script to figure out that there are no references to an object that can be </p>

When you run the example.php file on your server (or local host), you’ll see that the both constructor and destructor method automatically execute without needing to call them:

Output of PHP website template using oop techniques

PHP OOP Tutorials: