0
0
PHPprogramming~5 mins

Constructor promotion in PHP

Choose your learning style9 modes available
Introduction

Constructor promotion helps you write less code when creating classes. It lets you set up properties and their values quickly inside the constructor.

When you want to create a class with properties and set them right away.
When you want to avoid writing extra lines for declaring properties and assigning values.
When you want cleaner and shorter code for simple classes.
When you want to improve readability by combining property declaration and constructor parameters.
Syntax
PHP
class ClassName {
    public function __construct(private Type $property1, public Type $property2) {
        // no need to assign properties manually
    }
}

You declare properties directly in the constructor parameters using visibility keywords like public, private, or protected.

This feature was introduced in PHP 8.0.

Examples
This class has two properties, name and age, declared and assigned in the constructor.
PHP
<?php
class User {
    public function __construct(private string $name, public int $age) {}
}
Properties x and y have default values and are promoted in the constructor.
PHP
<?php
class Point {
    public function __construct(public float $x = 0.0, public float $y = 0.0) {}
}
Sample Program

This program creates a Product object using constructor promotion. It prints the product name and price.

PHP
<?php
class Product {
    public function __construct(public string $name, private float $price) {}

    public function getPrice(): float {
        return $this->price;
    }
}

$product = new Product("Book", 12.99);
echo "Product: " . $product->name . "\n";
echo "Price: $" . $product->getPrice() . "\n";
OutputSuccess
Important Notes

Constructor promotion only works with properties declared in the constructor parameters.

You can still add normal properties and methods outside the constructor.

Summary

Constructor promotion lets you declare and assign properties in one step inside the constructor.

It reduces code and improves readability for simple classes.

Use visibility keywords in constructor parameters to promote properties.