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
__construct
method 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.