Skip to Content
Course content

29: Named Arguments and Constructor Promotion

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've spent way too many hours in my career staring at a line of code like new User('John', 'Doe', true, false, null, 10) and wondering, "Wait, is the first boolean for isAdmin or isActive?"

When you're working on a small project, positional arguments are fine. But as your classes grow, you'll likely run into a situation like this. Let's look at a NewsletterSubscription class that handles how users sign up for emails.

class NewsletterSubscription {
    public function __construct(
        public string $email,
        public string $frequency = 'weekly',
        public bool $sendWelcomeEmail = true,
        public bool $trackAnalytics = true,
        public int $retryLimit = 3
    ) {}
}

// A developer wants to disable analytics and change the retry limit, 
// but keep everything else as default.
$sub = new NewsletterSubscription(
    'dev@example.com', 
    'weekly', 
    true, 
    false, 
    5
);

The "Comma Counting" Nightmare

Look at that instantiation. To change the retryLimit (the 5th argument), the developer was forced to pass in the default values for the frequency, sendWelcomeEmail, and trackAnalytics just to reach the end of the list.

This is fragile. If I, as the lead engineer, decide to add a new parameter—say, $timezone—right after the email address, every single one of these new NewsletterSubscription calls across the entire codebase will now be passing the wrong data into the wrong variables. The code might not even throw a Type Error if the types match, but your data will be corrupted.

Naming Your Arguments for Clarity

Since PHP 8.0, we have Named Arguments. Instead of relying on the order of the parameters, you can explicitly name the one you're targeting. This completely removes the need to pass "filler" defaults.

// Much cleaner. We only specify what we actually want to change.
$sub = new NewsletterSubscription(
    email: 'dev@example.com', 
    trackAnalytics: false, 
    retryLimit: 5
);

Now, it doesn't matter if the constructor has five arguments or fifty. If you only care about the email and the retry limit, you only provide those. It makes the code self-documenting; anyone reading this knows exactly what false and 5 refer to without having to jump back to the class definition.

Killing the Constructor Boilerplate

While we're cleaning up the constructor, let's talk about the "grunt work" of PHP classes. For years, we had to declare a property, then accept it in the constructor, then manually assign it using $this. It was repetitive and boring.

// The "Old Way" (Boilerplate City)
class User {
    public string $username;
    public string $email;

    public function __construct(string $username, string $email) {
        $this->username = $username;
        $this->email = $email;
    }
}

Constructor Property Promotion allows you to do all three steps—declaring the property, accepting the argument, and assigning it—in one single line. By adding a visibility modifier (like public, protected, or private) directly to the constructor argument, PHP handles the rest behind the scenes.

// The "Modern Way"
class User {
    public function __construct(
        public string $username, 
        public string $email
    ) {}
}

That's it. The curly braces are empty because PHP has already promoted those arguments to class properties. I personally love this because it reduces the "noise" in my files, making the actual logic of the class stand out rather than the setup code.




📋 Practical Task

Refactoring the E-commerce Product Catalog

You have been handed a legacy Product class that is far too verbose and difficult to instantiate. Your task is to modernize it.

Requirements:

  • Refactor the Product class to use Constructor Property Promotion.
  • The class should have the following properties: string $name, float $price, int $stock = 0, and bool $isDigital = false.
  • Below the class, instantiate a new Product object using Named Arguments.
  • The product should be named "Mechanical Keyboard", cost 129.99, and be marked as isDigital = false, but you should omit the stock argument entirely to let it use its default value.
<?php
// Your code here
?>
Rating
0 0

There are no comments for now.

to be the first to leave a comment.