← Back to PHP Course | Chapter 8: OOP | Lesson 3 of 14

PHP Constructors & Destructors

What is a Constructor?

A constructor is a special method named __construct() that PHP calls automatically the moment an object is created with new, making it the natural place to initialize required properties or validate input.

Example: What is a Constructor?

php
<?php
class User {
    function __construct() {
        echo "User object created!";
    }
}
new User();
?>

Constructors with Parameters

Constructor parameters let you require certain data up front, such as new User(Aditi, '[email protected]'), ensuring every object starts in a valid, fully-initialized state rather than needing manual setup afterward.

Example: Constructors with Parameters

php
<?php
class User {
    public $name;
    public $email;
    function __construct($name, $email) {
        $this->name = $name;
        $this->email = $email;
    }
}
$user = new User('Aditi', '[email protected]');
echo $user->name . " " . $user->email;
?>

Default Values in Constructors

A destructor is a special method named __destruct() that PHP calls automatically when an object is about to be destroyed, typically at the end of a script or when nothing references it anymore.

Example: Default Values in Constructors

php
<?php
class Logger {
    function __destruct() {
        echo "Logger destroyed";
    }
}
$log = new Logger();
?>

What is a Destructor?

Destructors are most useful for cleanup tasks like closing a file handle or a database connection that the object opened, so resources don't leak even if the code that created the object forgets to close them explicitly.

Example: What is a Destructor?

php
<?php
class FileHandler {
    function __destruct() {
        echo "Closing file handle";
    }
}
$file = new FileHandler();
?>

Constructor and Destructor Together

Unlike constructors, destructors are rarely written explicitly in typical PHP web code, since PHP's request lifecycle already cleans up resources at the end of each request — they matter more in long-running scripts.

Example: Constructor and Destructor Together

php
<?php
class Task {
    function __construct() {
        echo "Task started\n";
    }
    function __destruct() {
        echo "Task finished";
    }
}
$task = new Task();
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.