A constructor in PHP is a special method called automatically when an object is created. It is defined using __construct()
inside a class. Constructors are used to initialize object properties. They can accept parameters and set default values. PHP also supports type declarations in constructors for better data control.
1. Basic Constructor Example
class User {
public $name;
// Constructor method
public function __construct($userName) {
$this->name = $userName;
}
public function greet() {
return "Hello, " . $this->name;
}
}
$user = new User("John");
echo $user->greet(); // Output: Hello, John
File: constructor_basic.php
2. Constructor with Multiple Parameters
class Product {
public $name;
public $price;
public function __construct($name, $price) {
$this->name = $name;
$this->price = $price;
}
public function getDetails() {
return "Product: {$this->name}, Price: ₹{$this->price}";
}
}
$p = new Product("Laptop", 55000);
echo $p->getDetails();
File: product_constructor.php
3. Default Values in Constructor
class Student {
public $name;
public $grade;
public function __construct($name = "Unknown", $grade = "Not Assigned") {
$this->name = $name;
$this->grade = $grade;
}
public function display() {
return "{$this->name} is in grade {$this->grade}";
}
}
$s = new Student();
echo $s->display(); // Output: Unknown is in grade Not Assigned
File: default_constructor.php
4. Constructor with Type Declarations (PHP 7+)
class Employee {
public string $name;
public int $salary;
public function __construct(string $name, int $salary) {
$this->name = $name;
$this->salary = $salary;
}
public function getInfo() {
return "{$this->name} earns ₹{$this->salary}";
}
}
$emp = new Employee("Ravi", 30000);
echo $emp->getInfo();
File: typed_constructor.php
Summary Table
Feature | Example Code | Purpose |
---|---|---|
Constructor Definition | __construct() |
Initializes object when created |
Parameters in Constructor | __construct($name, $age) |
Sets initial values |
Default Values | __construct($x = 1) |
Optional constructor values |
Type Declarations (PHP 7+) | string $name in __construct() |
Enforces data types |