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.

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.

This 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()
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
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.

Constructor property promotion

From PHP 8, we can simplify the construction process by using constructor parameters as properties. This feature is called constructor property promotion.

Let’s take our earlier constructor as an example.

  1. We create properties in the class.
  2. Then we create parameters for the constructor.
  3. Finally we assign the value of the parameters to the properties.
Example: normal construction
// Properties
var $firstName = "Unknown";
var $lastName  = "Unknown";

// Constructor with parameters
function __construct($fName, $lName) {
    // Assign constructor parameter
    // values to class properties
    $this->firstName = $fName;
    $this->lastName  = $lName;
}

With constructor property promotion, we create the properties only once in the constructor’s parameter list.

Example: new construction
public function __construct(
    private string $fName = "Unknown",
    private string $lName = "Unknown",
) { }

note PHP will take this shortened syntax and transform it back to the original under the hood.

That’s all there is to constructor property promotion, but there is a little caveat here.

Even though it’s good practice, we don’t normally have to specify access modifiers for class members. When we use constructor property promotion however, we do have to specify them.

Access modifiers are the public and private keywords you see for the constructor and its parameters. We cover them a little later in the course in the Encapsulation lesson.

So with constructor property promotion, our Person class from earlier should now look as follows.

Example: new Person class constructor
class Person {

    public function __construct(
        private string $fName = "Unknown",
        private string $lName = "Unknown",
    ) { }

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

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

echo "<br>";

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

If we take a look in the browser, everything still works as expected.

Method name as class name for a constructor

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

When a method inside a class has the same name as the class itself, the method becomes a constructor.

In older versions of PHP, the __construct() didn’t exist. Instead, we used a method with the same name as the class.

Example:
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();

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.

We create a destructor with the __destruct() method and define our cleanup logic inside.

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 handling .

Don’t worry if some of the code doesn’t make sense, it’s just the concept we want you to understand.

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 {
        var $fileHandle;

        public function __construct(private $file) {
            $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() method.

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.
  • From PHP 8 we can simplify the construction process and define properties directly in the constructor’s parameter list.
    • A constructor using property promotion must have access modifiers set for the function as well as the parameters.
  • A destructor will clean up any resources that a class may be using.