PHP OOP Class Constructors & Destructors Tutorial

In this tutorial we learn about the special methods that construct and destruct an instance of a class with default values when the class is instantiated.

Here's a table of contents of what you'll learn in this lesson:
(click on a link to skip to its section)

Let's jump right in.

What is a constructor?

When we create an instance object of a class, we usually need to set the attribute values to custom values before we can effectively use them.

We can create and initialize an instanced object in one step with a constructor method. A constructor method will construct the object by assigning values to the attributes when the object is created.

How to create a constructor

PHP provides us with a special __construct() method to use to construct an object.

The __construct() method is set up with parameters that will input their values into the attributes we choose.

Syntax:
var $attribute = "value";

function __construct($newValue) {
    $this->attribute = $newValue;
}

When creating the class object, we can now enter a value in between the parentheses. The value will then be assigned to the attribute.

Example: create a constructor with __construct()
<?php
    class Person {
        // Attributes
        var $firstName = "Unknown";
        var $lastName = "Unknown";

        function __construct($fName, $lName) {
            $this->firstName = $fName;
            $this->lastName = $lName;
        }

        // Methods
        function introduction() {
            echo "Hi, my name is " . $this->firstName . " " . $this->lastName;
        }
    }

    $person1 = new Person("John","Wick");
    $person1->introduction();

    echo "<br>";

    $person2 = new Person("Jane", "Doe");
    $person2->introduction();

?>

In the example above, we want the constructor to immediately create the object with a first and last name.

When we create the two person objects, we pass the names into the parentheses directly, this calls the constructor and it will assign the names we enter to the attributes.

It allows us to skip the step of doing it manually with each attribute.

Example: manual construction
<?php
    class Person {
        // Attributes
        var $firstName = "Unknown";
        var $lastName = "Unknown";

        // Methods
        function introduction() {
            echo "Hi, my name is " . $this->firstName . " " . $this->lastName;
        }
    }

    // Manual construction
    $person1 = new Person();
    $person1->firstName = "John";
    $person1->lastName = "Wick";
    $person1->introduction();

?>

The result may be the same but the constructor allows us to type a lot less code.

Class name as method name

When a method inside a class has the same name as the class itself, the method is a constructor. In older versions of PHP, the __construct() method wasn’t used as a constructor, instead we used a method with the same name as the class.

Example:
<?php
    class Person {
        // Attributes
        var $firstName = "Unknown";
        var $lastName = "Unknown";

        function Person($fName, $lName) {
            $this->firstName = $fName;
            $this->lastName = $lName;
        }

        // Methods
        function introduction() {
            echo "Hi, my name is " . $this->firstName . " " . $this->lastName;
        }
    }

    $person1 = new Person("John","Wick");
    $person1->introduction();

    echo "<br>";

    $person2 = new Person("Jane", "Doe");
    $person2->introduction();

?>

This style of constructor is deprecated in PHP 7 and above. We should always use the __construct() method as the constructor.

How to create a destructor

When an object is not being used anymore, or when the garbage collector runs, we can use a destructor to clean up any resources that the class may be using.

Syntax:
__destruct() {
    // clean up code here
}

As an example, let’s consider that we have an open file we are working with. We will use the text file from the tutorial lesson on file handlingOpens up in a new page

File:: file.txt
Best movies of all time:
1. The Godfather
2. Star Wars: Episode V
3. The Dark Knight
4. Pulp Fiction
5. Back To The Future
6. Alien
7. Fight Club
8. Die Hard
9. Jurassic Park
10. Inception

We create a very simple class to work with the file. The destructor contains a method to close the file so whenever the destructor is called, we can be sure the file is closed.

Example: main.php
<div style="white-space: pre">
<?php
    class FileOp {
        // Attributes
        var $file;
        var $fileHandle;

        function __construct($fName) {
            $this->file = $fName;
            $this->fileOpenRead($this->file);
        }

        function __destruct() {
            fclose($this->fileHandle);
            echo "<br><strong>File closed</strong>";
        }

        // Methods
        function fileOpenRead($fileName) {
            $this->fileHandle = fopen($fileName, "r") or die ("File operation unsuccessful");
        }

        function fileRead() {
            echo fread($this->fileHandle, filesize($this->file));
        }

    }

    $book1 = new FileOp("file.txt");
    $book1->fileRead();

?>
</div>

When we run the example above, it prints out the content of file.txt. Because we don’t use the object after the file is read, it calls the destructor and the file is closed through the fclose() function.

Summary: Points to remember

  • A constructor will assign values to its attributes when an object is instantiated.
  • To create a constructor, we use the special __construct() method instead of the older style of naming a method the same as the class itself.
  • A destructor will clean up any resources that a class may be using.