Constructor Property Promotion in PHP: Tutorial & Examples

Updated: February 22, 2024 By: Guest Contributor Post a comment

Introduction

One of the significant enhancements in PHP 8 is constructor property promotion. This feature aims to reduce boilerplate code associated with class property declaration and initialization in constructors. In traditional PHP classes, you typically declare class properties at the top of the class, then redeclare each property as a constructor parameter and finally, manually assign each parameter to its corresponding property inside the constructor. Such repetition is not only tedious but also prone to errors. Constructor property promotion addresses this by allowing properties to be declared and assigned within the constructor signature itself.

In this tutorial, we delve into the intricacies of constructor property promotion in PHP, starting from basic examples and progressively exploring more complex scenarios. We’ll demonstrate how this feature can streamline your code and make it more readable and concise.

Basic Example

class Person {
    public function __construct(private string $name, private int $age) {}
    
    public function getName(): string {
        return $this->name;
    }
    
    public function getAge(): int {
        return $this->age;
    }
}

$person = new Person('John Doe', 30);
echo $person->getName();
// Output: John Doe
echo $person->getAge();
// Output: 30

Understanding Constructor Property Promotion

Constructor property promotion allows you to declare a property’s visibility (public, protected, or private), its name, and optionally its type, directly in the constructor’s parameter list. The compiler then automatically generates the corresponding property and initializes it with the provided argument when creating an object.

Intermediary Example

class Book {
    public function __construct(private string $title, private string $author, private int $publishedYear) {}
    
    public function getDetails(): string {
        return "$this->title by $this->author, published in $this->publishedYear";
    }
}

$book = new Book('PHP for Beginners', 'Jane Doe', 2021);
echo $book->getDetails();
// Output: PHP for Beginners by Jane Doe, published in 2021

Advanced Uses

Constructor property promotion can be seamlessly integrated with other features such as default values, nullable types, and inheritance. Let’s explore some advanced examples that harness these capabilities.

Default Values & Nullable Types

class Conference {
    public function __construct(private string $name, private ?string $location = null, private int $year, private ?int $attendeeCount = null) {}
    
    public function getInfo(): string {
        $locationInfo = $this->location ? " in $this->location" : '';
        $attendeeInfo = $this->attendeeCount ? ", with $this->attendeeCount attendees" : '';
        return "$this->name$locationInfo, $year$attendeeInfo";
    }
}

$conference = new Conference('PHPCon', null, 2023);
echo $conference->getInfo();
// Output: PHPCon, 2023

Inheritance and Constructor Property Promotion

class SpecialBook extends Book {
    public function __construct(private string $specialFeature, ...$args) {
        parent::__construct(...$args);
    }
    
    public function getSpecialFeature(): string {
        return $this->specialFeature;
    }
}

$aSpecialBook = new SpecialBook('Autographed', 'Advanced PHP Programming', 'Eve Adams', 2022);
echo $aSpecialBook->getDetails();
// Additional Output: Autographed

Conclusion

Constructor property promotion in PHP signifies a paradigm shift towards more elegant and succinct code. By leveraging this feature, developers can significantly reduce the repetition commonly associated with property declaration and initialization. Whether you’re working on a simple class or a more complex hierarchy involving inheritance, constructor property promotion can streamline your coding workflow and enhance readability. It’s a welcome enhancement that underscores PHP’s evolution and its commitment to facilitating better coding practices.