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
PHP OOP Introduction
PHP Class
PHP Objects
Exercises & Assignments
No Content Found.
Interview Questions & Answers
How to create a class and object in PHP?
What is the difference between public, private and protected in PHP?
Is multiple inheritance supported in PHP?
What is the meaning of final class and final method in PHP?
What is the difference between abstract class and interface in PHP?
What are traits in PHP?
What is a constructor in PHP?