PHP Constructor
Initializing objects automatically
🚀 What is a Constructor?
A constructor is a special method that automatically runs when an object is created. It's used to initialize object properties with values, making object creation easier and more efficient.
<?php
class Person {
public $name;
public $age;
// Constructor
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
public function introduce() {
return "Hi, I'm $this->name and I'm $this->age years old.";
}
}
$person = new Person("John", 25);
echo $person->introduce();
?>
Output:
Hi, I'm John and I'm 25 years old.
Constructor Features
Auto-Execute
Runs automatically when object is created
$obj = new MyClass();
// Constructor runs here
Initialize Properties
Set initial values for object properties
public function __construct() {
$this->value = 0;
}
Accept Parameters
Receive values during object creation
public function __construct($x) {
$this->x = $x;
}
Setup Tasks
Perform initialization operations
public function __construct() {
$this->connect();
}
🔹 Basic Constructor
The constructor method is named
__construct()
with two underscores. It's called automatically when you create a new object using the
new
keyword.
<?php
class Car {
public $brand;
public $model;
public function __construct($brand, $model) {
$this->brand = $brand;
$this->model = $model;
echo "New car created: $brand $model
";
}
}
$car1 = new Car("Toyota", "Camry");
$car2 = new Car("Honda", "Civic");
?>
Output:
New car created: Toyota Camry
New car created: Honda Civic
🔹 Constructor with Default Values
You can provide default parameter values in constructors. If no value is passed during object creation, the default value is used automatically.
<?php
class Product {
public $name;
public $price;
public $stock;
public function __construct($name, $price = 0, $stock = 0) {
$this->name = $name;
$this->price = $price;
$this->stock = $stock;
}
public function getInfo() {
return "$this->name - Price: $$this->price, Stock: $this->stock";
}
}
$product1 = new Product("Laptop", 999, 50);
$product2 = new Product("Mouse"); // Uses default price and stock
echo $product1->getInfo();
echo $product2->getInfo();
?>
Output:
Laptop - Price: $999, Stock: 50
Mouse - Price: $0, Stock: 0
🔹 Constructor Without Parameters
Constructors don't always need parameters. They can set default values or perform setup tasks without receiving external data.
<?php
class Counter {
public $count;
public function __construct() {
$this->count = 0;
echo "Counter initialized to 0
";
}
public function increment() {
$this->count++;
}
public function getValue() {
return "Current count: $this->count";
}
}
$counter = new Counter();
$counter->increment();
$counter->increment();
echo $counter->getValue();
?>
Output:
Counter initialized to 0
Current count: 2
🔹 Practical Example
Here's a real-world example showing how constructors simplify object creation and ensure proper initialization.
<?php
class User {
public $username;
public $email;
public $role;
public $createdAt;
public function __construct($username, $email, $role = "member") {
$this->username = $username;
$this->email = $email;
$this->role = $role;
$this->createdAt = date("Y-m-d H:i:s");
}
public function getProfile() {
return "User: $this->username ($this->role)
" .
"Email: $this->email
" .
"Joined: $this->createdAt";
}
}
$user1 = new User("john_doe", "[email protected]", "admin");
$user2 = new User("jane_smith", "[email protected]");
echo $user1->getProfile();
echo "
";
echo $user2->getProfile();
?>
Output:
User: john_doe (admin)
Email: [email protected]
Joined: 2025-02-10 14:30:00
User: jane_smith (member)
Email: [email protected]
Joined: 2025-02-10 14:30:00