PHP Constructors & Destructors
Constructors and Destructors in PHP
Constructors and destructors are special methods in PHP classes that are automatically called when an object is created or destroyed. They help in initializing and cleaning up resources respectively.
Constructors
Basic Constructor
A constructor is called when an object is instantiated. In PHP, the
constructor method is named __construct()
.
<?php
class Car {
public $model;
// Constructor
public function __construct() {
$this->model = "Unknown";
echo "A new car object has been created.\n";
}
}
// Create object
$myCar = new Car();
echo "Model: " . $myCar->model . "\n";
?>
Output:
A new car object has been created. Model: Unknown
Constructor with Parameters
Constructors can accept parameters to initialize object properties.
<?php
class Book {
public $title;
public $author;
public function __construct($title, $author) {
$this->title = $title;
$this->author = $author;
echo "Book '{$this->title}' created.\n";
}
}
$myBook = new Book("PHP for Beginners", "John Doe");
echo "Title: {$myBook->title}, Author: {$myBook->author}\n";
?>
Output:
Book 'PHP for Beginners' created. Title: PHP for Beginners, Author: John Doe
Constructor Property Promotion (PHP 8+)
PHP 8 introduced constructor property promotion to simplify property declaration and assignment.
<?php
class Product {
// Properties are declared and assigned directly in constructor parameters
public function __construct(
public string $name,
public float $price,
public int $quantity = 1
) {
echo "Product {$this->name} initialized.\n";
}
}
$laptop = new Product("Laptop", 999.99, 2);
echo "{$laptop->name}, Price: \${$laptop->price}, Qty: {$laptop->quantity}\n";
?>
Output:
Product Laptop initialized. Laptop, Price: $999.99, Qty: 2
Destructors
A destructor is called when an object is destroyed. The destructor
method is named __destruct()
.
<?php
class FileHandler {
private $file;
public function __construct($filename) {
$this->file = fopen($filename, 'w');
echo "File {$filename} opened for writing.\n";
}
public function write($content) {
fwrite($this->file, $content);
}
public function __destruct() {
if ($this->file) {
fclose($this->file);
echo "File closed and resources released.\n";
}
}
}
$handler = new FileHandler("test.txt");
$handler->write("Hello, PHP!");
// Destructor is called automatically when script ends or object is unset
?>
Output:
File test.txt opened for writing. File closed and resources released.
Inheritance with Constructors/Destructors
When dealing with inheritance, parent constructors/destructors are not called automatically.
<?php
class Animal {
protected $name;
public function __construct($name) {
$this->name = $name;
echo "Animal {$this->name} created.\n";
}
public function __destruct() {
echo "Animal {$this->name} destroyed.\n";
}
}
class Dog extends Animal {
private $breed;
public function __construct($name, $breed) {
parent::__construct($name); // Call parent constructor
$this->breed = $breed;
echo "Dog of breed {$this->breed} created.\n";
}
public function __destruct() {
echo "Dog {$this->name} destroyed.\n";
parent::__destruct(); // Call parent destructor
}
}
$myDog = new Dog("Buddy", "Golden Retriever");
// Destructor will be called at the end of script
?>
Output:
Animal Buddy created. Dog of breed Golden Retriever created. Dog Buddy destroyed. Animal Buddy destroyed.
Practical Examples
Database Connection Example
<?php
class Database {
private $connection;
public function __construct($host, $user, $pass, $db) {
$this->connection = new mysqli($host, $user, $pass, $db);
if ($this->connection->connect_error) {
die("Connection failed: " . $this->connection->connect_error);
}
echo "Connected to database successfully.\n";
}
public function query($sql) {
return $this->connection->query($sql);
}
public function __destruct() {
if ($this->connection) {
$this->connection->close();
echo "Database connection closed.\n";
}
}
}
// Usage
$db = new Database("localhost", "username", "password", "testdb");
$result = $db->query("SELECT * FROM users");
// Process results...
// Destructor will close connection automatically
?>
Output:
Connected to database successfully. Database connection closed.
Shopping Cart Example
<?php
class ShoppingCart {
private $items = [];
private static $cartCount = 0;
public function __construct() {
self::$cartCount++;
echo "Shopping cart created. Total carts: " . self::$cartCount . "\n";
}
public function addItem($item) {
$this->items[] = $item;
echo "Added {$item} to cart.\n";
}
public function __destruct() {
self::$cartCount--;
echo "Cart destroyed. Items removed: " . count($this->items) . "\n";
echo "Remaining carts: " . self::$cartCount . "\n";
}
}
$cart1 = new ShoppingCart();
$cart1->addItem("Laptop");
$cart1->addItem("Mouse");
$cart2 = new ShoppingCart();
$cart2->addItem("Keyboard");
unset($cart1); // Explicitly destroy first cart
?>
Output:
Shopping cart created. Total carts: 1 Added Laptop to cart. Added Mouse to cart. Shopping cart created. Total carts: 2 Added Keyboard to cart. Cart destroyed. Items removed: 2 Remaining carts: 1 Cart destroyed. Items removed: 1 Remaining carts: 0
Key Points to Remember
-
Constructors (
__construct()
) are called when an object is created -
Destructors (
__destruct()
) are called when an object is destroyed - Parent constructors/destructors are not called automatically in inheritance
-
Destructors are called when:
- Script execution ends
-
Object is explicitly destroyed with
unset()
- No more references to the object exist
- PHP 8's constructor property promotion reduces boilerplate code
- Destructors are useful for resource cleanup (file handles, database connections, etc.)