What if you could cut your class code in half and avoid silly mistakes with just one simple trick?
Why Constructor promotion in PHP? - Purpose & Use Cases
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.
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.
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.
class Person {
public string $name;
public int $age;
public function __construct(string $name, int $age) {
$this->name = $name;
$this->age = $age;
}
}class Person {
public function __construct(public string $name, public int $age) {}
}You can write classes faster and with less chance of errors, making your code cleaner and easier to maintain.
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.
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.