Constructor in PHP
In PHP, the __construct method is a special method known as a constructor. It is automatically called when an instance of a class is created. Constructors are used to initialize object properties or perform any setup required when an object is instantiated.
Defining a Constructor
To define a constructor in a class, use the __construct method. You can include parameters in the constructor to pass values during object creation.
<?php
class Car {
public $make;
public $model;
public $year;
// Constructor method
public function __construct($make, $model, $year) {
$this->make = $make;
$this->model = $model;
$this->year = $year;
}
// Method to display car information
public function getCarInfo() {
return "{$this->year} {$this->make} {$this->model}";
}
}
// Create an instance of the Car class
$myCar = new Car("Toyota", "Corolla", 2020);
// Display car information
echo $myCar->getCarInfo(); // Outputs: 2020 Toyota Corolla
?>
Constructor Overloading
PHP does not support method overloading directly. If you need to handle different ways to create objects, you can use optional parameters or check the number of arguments inside the constructor.
<?php
class Person {
public $name;
public $age;
// Constructor with default values
public function __construct($name = "Unknown", $age = 0) {
$this->name = $name;
$this->age = $age;
}
public function getInfo() {
return "Name: {$this->name}, Age: {$this->age}";
}
}
// Create instances of Person with different arguments
$person1 = new Person("Alice", 30);
$person2 = new Person(); // Uses default values
echo $person1->getInfo(); // Outputs: Name: Alice, Age: 30
echo $person2->getInfo(); // Outputs: Name: Unknown, Age: 0
?>
Calling Parent Constructor
If a class extends another class, it is often necessary to call the parent class’s constructor from the child class’s constructor. Use the parent::__construct() method to achieve this.
<?php
class Vehicle {
public $type;
public function __construct($type) {
$this->type = $type;
}
}
class Car extends Vehicle {
public $model;
public function __construct($type, $model) {
parent::__construct($type); // Call the parent constructor
$this->model = $model;
}
public function getCarInfo() {
return "{$this->type} - {$this->model}";
}
}
// Create an instance of Car
$myCar = new Car("Sedan", "Toyota Corolla");
echo $myCar->getCarInfo(); // Outputs: Sedan - Toyota Corolla
?>
Key Points
- Automatic Invocation: The
__constructmethod is automatically called when an object is instantiated. - Initialization: Use the constructor to initialize object properties or perform setup tasks.
- Optional Parameters: Constructors can have optional parameters with default values.
- Parent Constructor: Use
parent::__construct()to call the constructor of the parent class.
Constructor Property Promotion (PHP 8+)
Reduce boilerplate by declaring properties in the constructor signature:
class User {
public function __construct(
public readonly int $id,
public string $name,
private string $passwordHash,
) {}
}
$user = new User(1, 'Alice', '$2y$...');
echo $user->name; // Alice
Named Arguments (PHP 8+)
Pass constructor arguments by name for clarity:
$car = new Car(year: 2024, make: 'Toyota', model: 'Camry');
Disabling the Constructor
Use a private constructor for singleton or factory patterns:
class Database {
private static ?self $instance = null;
private function __construct() {}
public static function getInstance(): self {
return self::$instance ??= new self();
}
}
Clone and Copy Semantics
PHP performs shallow copy on clone. Override __clone() for deep copies:
class Report {
public function __construct(private array $data) {}
public function __clone(): void {
$this->data = array_map(fn($item) => clone $item, $this->data);
}
}
Common Pitfalls
- Heavy I/O in constructors makes testing difficult — inject dependencies instead.
- Forgetting
parent::__construct()when the parent has required initialization. - Using constructors for logic that belongs in factory methods (
User::fromArray($data)).