What is a constructor in PHP?

A constructor is a special method that runs automatically when an object is created. In PHP it is written as __construct(). It is mostly used to set the starting values of the object.

A destructor, written as __destruct(), is the opposite. It runs when the object is destroyed, or when the script ends.

<?php
class Student {
    public $name;

    public function __construct($name) {
        $this->name = $name;
        echo "Object created for " . $name . "<br>";
    }

    public function __destruct() {
        echo "Object for " . $this->name . " is destroyed";
    }
}

$s = new Student("Robin");
echo "Script is running...<br>";
?>

Output:

Tutorials Class - Output Window

Object created for Robin
Script is running…
Object for Robin is destroyed

From PHP 8.0 you can write a shorter constructor using constructor property promotion. The property is declared and set in the constructor line itself.

<?php
class Student {
    public function __construct(public string $name) {}
}

$s = new Student("Robin");
echo $s->name;
?>

Output:

Tutorials Class - Output Window

Robin


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.