I was recently reviewing a PHP project. The code worked fine. Tests were passing. No bugs.
But something caught my eye.
The same pattern was repeated again and again in almost every class constructor. It’s not wrong, but since PHP 8.0, we don’t need to write it this way anymore.
This post is a quick, practical PHP tip about classes and constructors that can make your code cleaner, shorter, and easier to read.
The Old Habit We Still Write
This is something I still see in many real projects:
class UserService
{
private string $name;
private int $age;
public function __construct(string $name, int $age)
{
$this->name = $name;
$this->age = $age;
}
}
Nothing is technically wrong here.
But when a project has:
- 50+ classes
- Each class has 5–10 properties
You end up writing the same lines again and again.
It’s boring, repetitive, and easy to mess up when refactoring.
PHP 8.0 Changed This Forever
Since PHP 8.0, we have a feature called:
Constructor Property Promotion
It lets you declare and assign class properties directly inside the constructor.
Let’s rewrite the same class.
The Modern Way (Cleaner & Shorter)
class UserService
{
public function __construct(
private string $name,
private int $age
) {
}
}
That’s it.
What Just Happened?
- No separate property declaration
- No
$this->name = $name; - Same behavior
- Less code
- Easier to read
Your brain now focuses on what the class needs, not boilerplate code.
Public, Protected, or Private? Your Choice
You’re not limited to private. You can use any visibility.
class Post
{
public function __construct(
public string $title,
public string $content,
private int $authorId
) {
}
}
This works exactly as expected.
A Real-Life Refactor Story
While reviewing a Laravel project, I found a service class with 12 properties.
The constructor alone was almost 30 lines long.
I did this:
- Selected the constructor
- Used VS Code Quick Edit / Multi-cursor
- Converted all properties to constructor promotion
The result:
- Constructor went from 30 lines to 6 lines
- No logic changed
- Code became easier to scan during reviews
This refactor took less than 2 minutes.
When You Should Use This
Constructor property promotion is perfect when:
- Properties are only set in the constructor
- You don’t need extra logic during assignment
- You want clean, modern PHP code
When You Should NOT Use It
Avoid it if:
- You need validation before assignment
- You modify values before storing them
- You want to keep constructor logic very explicit
Example where the old way is still better:
public function __construct(string $email)
{
$this->email = strtolower($email);
}
Top comments (0)