__construct()) & Constructor PromotionA constructor is a magic method (__construct()) that executes automatically when a new instance of a class is created. PHP 8 introduced Constructor Property Promotion, allowing properties to be declared and initialized directly inside the constructor signature.
// Traditional Constructor
class User {
public string $name;
public function __construct(string $name) {
$this->name = $name;
}
}
// Modern PHP 8 Constructor Property Promotion!
class User {
public function __construct(public string $name) {}
}
flowchart LR
A["new User('Maksudur', 28)"] --> B["__construct() Invoked"]
B --> C["Promoted Properties Initialized Automatically"]
C --> D["Instance Ready for Method Invocations"]
<?php
declare(strict_types=1);
class CustomerOrder
{
// Modern PHP 8 Constructor Property Promotion
public function __construct(
public int $orderId,
public string $customerName,
public float $amount,
public string $status = 'pending' // Default parameter
) {
// Validation inside constructor
if ($amount <= 0) {
throw new InvalidArgumentException("Order amount must be greater than zero.");
}
}
public function getOrderSummary(): string
{
return "Order #{$this->orderId} for {$this->customerName} - Total: ${$this->amount} [Status: {$this->status}]";
}
}
// Instantiating object using promoted constructor
$order = new CustomerOrder(1001, "Maksudur", 249.50);
echo $order->getOrderSummary() . "
";
$status = 'pending') for optional constructor arguments.Refactor a class User to use PHP 8 Constructor Property Promotion to initialize public string $email and public int $id!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.