0
0
PHPprogramming~5 mins

__construct and __destruct in PHP

Choose your learning style9 modes available
Introduction

These special methods help set up and clean up objects automatically when you create or remove them.

When you want to give initial values to an object right after creating it.
When you need to close files or free resources when an object is no longer needed.
When you want to print a message or log something when an object starts or ends.
When you want to prepare an object with some setup steps automatically.
When you want to make sure cleanup happens without forgetting it.
Syntax
PHP
<?php
class ClassName {
    public function __construct() {
        // code to run when object is created
    }

    public function __destruct() {
        // code to run when object is destroyed
    }
}
?>

The __construct method runs automatically when you create a new object.

The __destruct method runs automatically when the object is removed or script ends.

Examples
This example shows messages when a Car object is created and destroyed.
PHP
<?php
class Car {
    public function __construct() {
        echo "Car created!\n";
    }

    public function __destruct() {
        echo "Car destroyed!\n";
    }
}

$myCar = new Car();
?>
This example sets a name when creating a Person and says goodbye when the object is destroyed.
PHP
<?php
class Person {
    private string $name;

    public function __construct(string $name) {
        $this->name = $name;
        echo "Hello, $name!\n";
    }

    public function __destruct() {
        echo "{$this->name} says goodbye!\n";
    }
}

$person = new Person("Anna");
?>
Sample Program

This program creates a Book object that announces when it opens and closes. The destructor runs automatically at the end.

PHP
<?php
class Book {
    private string $title;

    public function __construct(string $title) {
        $this->title = $title;
        echo "Opening book: $title\n";
    }

    public function __destruct() {
        echo "Closing book: {$this->title}\n";
    }
}

$book = new Book("Learn PHP");
echo "Reading the book...\n";
// The destructor will run automatically at the end of the script
?>
OutputSuccess
Important Notes

You do not call __construct or __destruct yourself; PHP calls them automatically.

The destructor is useful for cleanup like closing files or database connections.

If you create multiple objects, each will run its own constructor and destructor.

Summary

__construct runs when an object is created to set it up.

__destruct runs when an object is removed to clean up.

They help automate starting and ending tasks for objects.