Constructor Promotion (8.0)
Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 42 of 91.
PHP 8.0 introduced constructor promotion, a feature that dramatically reduces boilerplate code when defining classes. Instead of declaring properties separately and then assigning them in the constructor, you can do both in one step.
Here's the traditional approach you've been using:
<?php
class Product {
private string $name;
private float $price;
public function __construct(string $name, float $price) {
$this->name = $name;
$this->price = $price;
}
public function getInfo(): string {
return $this->name . ": $" . $this->price;
}
}
With constructor promotion, you add the access modifier directly to the constructor parameters:
<?php
class Product {
public function __construct(
private string $name,
private float $price
) {}
public function getInfo(): string {
return $this->name . ": $" . $this->price;
}
}
$product = new Product("Laptop", 999.99);
echo $product->getInfo();
Output:
Laptop: $999.99By adding private, protected, or public before a constructor parameter, PHP automatically creates the property and assigns the value. You can mix promoted and regular parameters in the same constructor, and you can still add logic inside the constructor body if needed.
Key Point: Constructor promotion eliminates repetitive property declarations and assignments, making your classes cleaner and easier to read while maintaining full encapsulation control.
Challenge
EasyLet's build a contact management system that showcases the elegance of constructor promotion. You'll create a clean, modern PHP class that eliminates boilerplate code while maintaining proper encapsulation.
You'll organize your code across two files:
Contact.php— Create aContactclass using constructor promotion to define all properties directly in the constructor signature. Your contact should have:- A private
$nameproperty (string) - A private
$emailproperty (string) - A private
$phoneproperty (string) with a default value of"Not provided"
getFullDetails()that returns"[name] | [email] | [phone]". Also add a methodgetSummary()that returns"Contact: [name]".- A private
main.php— Include the Contact file. You'll receive three inputs: a name, an email, and a phone number. Create twoContactinstances:- The first contact should use all three values (name, email, and phone)
- The second contact should use only the name and email (relying on the default phone value)
- The full details of the first contact
- The summary of the first contact
- The full details of the second contact
- The summary of the second contact
Notice how constructor promotion lets you define properties, set their visibility, declare their types, and assign values — all in a single, readable constructor signature. The optional phone parameter with a default value demonstrates that promoted parameters work seamlessly with default values, just like regular parameters.
Cheat sheet
PHP 8.0 introduced constructor promotion, which allows you to declare and initialize class properties directly in the constructor parameters by adding an access modifier.
Traditional approach:
<?php
class Product {
private string $name;
private float $price;
public function __construct(string $name, float $price) {
$this->name = $name;
$this->price = $price;
}
}
With constructor promotion:
<?php
class Product {
public function __construct(
private string $name,
private float $price
) {}
}
$product = new Product("Laptop", 999.99);
By adding private, protected, or public before a constructor parameter, PHP automatically creates the property and assigns the value.
You can use default values with promoted parameters:
<?php
class Contact {
public function __construct(
private string $name,
private string $email,
private string $phone = "Not provided"
) {}
}
Constructor promotion can be mixed with regular parameters, and you can still add logic inside the constructor body if needed.
Try it yourself
<?php
require_once 'Contact.php';
// Read input
$name = trim(fgets(STDIN));
$email = trim(fgets(STDIN));
$phone = trim(fgets(STDIN));
// TODO: Create first contact with all three values (name, email, phone)
// TODO: Create second contact with only name and email (use default phone)
// TODO: Print full details of first contact
// TODO: Print summary of first contact
// TODO: Print full details of second contact
// TODO: Print summary of second contact
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe $this KeywordMethodsPropertiesConstructor (__construct)Destructor (__destruct)Recap - Simple Calculator4Inheritance
Basic InheritanceThe parent:: KeywordMethod OverridingThe final KeywordAbstract ClassesRecap - Employee Hierarchy7Encapsulation
Public, Protected, PrivateAccess Modifiers in DepthGetters and SettersInformation HidingConstructor Promotion (8.0)Recap - Student Records System2Namespaces & Autoloading
Introduction to NamespacesThe use KeywordPSR-4 Autoloading StandardComposer AutoloaderRecap - Organized Project5Interfaces & Contracts
Introduction to InterfacesImplementing InterfacesMultiple Interface ImplementInterface vs Abstract ClassType Hinting with InterfacesRecap - Shape Calculator8Magic Methods
Magic Methods Introduction__toString & __debugInfo__get, __set, __isset, __unset__call & __callStatic__clone & Object Cloning__serialize & __unserializeRecap - Custom Collection11Type System & Error Handling
Type DeclarationsNullable TypesUnion & Intersection TypesException ClassesCustom Exception HierarchyTry, Catch, FinallyRecap - Form Validator14Project: Library Management
Project OverviewBook and User Classes3Class Properties
Instance vs Static PropertiesConstants in ClassesStatic Methods & PropertiesPrivate & Protected PropertiesReadonly Properties (PHP 8.1)Recap - Bank Account Manager6Polymorphism
Method Overriding RevisitedPolymorphism via InterfacesType Hinting & Union TypesLate Static BindingRecap - Payment Processor9Traits
Introduction to TraitsUsing Multiple TraitsTrait Conflict ResolutionAbstract Methods in TraitsTraits vs Inheritance12Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern