0
0
PHPprogramming~3 mins

Why Constructor promotion in PHP? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could cut your class code in half and avoid silly mistakes with just one simple trick?

The Scenario

Imagine you want to create a class in PHP that holds some data, like a person's name and age. You write a constructor to set these values and also declare properties for them. Doing this for many classes or many properties means writing a lot of repetitive code.

The Problem

This manual way is slow and boring because you have to write the same lines over and over: declaring properties, writing the constructor parameters, and assigning values inside the constructor. It's easy to make mistakes, like forgetting to assign a value or mismatching names.

The Solution

Constructor promotion lets you declare and initialize properties directly in the constructor parameters. This means less code, fewer mistakes, and your class looks cleaner and easier to read.

Before vs After
Before
class Person {
  public string $name;
  public int $age;

  public function __construct(string $name, int $age) {
    $this->name = $name;
    $this->age = $age;
  }
}
After
class Person {
  public function __construct(public string $name, public int $age) {}
}
What It Enables

You can write classes faster and with less chance of errors, making your code cleaner and easier to maintain.

Real Life Example

When building a user profile system, you often create many classes with similar properties. Constructor promotion helps you quickly set up these classes without repetitive code.

Key Takeaways

Constructor promotion reduces repetitive code in class definitions.

It combines property declaration and initialization in one step.

This leads to cleaner, easier-to-read, and less error-prone code.