PHP
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions
-
Section 4: Object-Oriented PHP
-
Section 5: Working with Data
-
Section 6: Modern PHP (PHP 8)
-
Section 7: Working with Files and Networking
-
Section 8: Common PHP Frameworks Overview
-
Section 9: Tooling and Ecosystem
-
Section 10: Practical Projects
-
Section 11: Interview Practice
-
Section 12: More Standard Library
-
Section 13: Data Structures and Algorithms in PHP
-
Section 14: More Practice Exercises
-
Section 15: More Security and Best Practices
-
Section 16: More Testing and Tooling
-
Section 17: WordPress-Style CMS Concepts
-
Section 18: Advanced OOP Practice
-
Section 19: More Web Fundamentals
-
Section 20: Database Practice
-
Section 21: PHP Manual: Array Functions
-
Section 22: PHP Manual: Date and Calendar Functions
-
Section 23: PHP Manual: Filesystem and Directory Functions
-
Section 24: PHP Manual: Filter and Var Handling
-
Section 25: PHP Manual: Math Functions
-
Section 26: PHP Manual: JSON and XML
-
Section 27: PHP Manual: Network and Stream Functions
-
Section 28: PHP Manual: Error and Exception Handling
-
Section 29: PHP Manual: Output Control and Misc
-
Section 30: PHP Manual: FTP, Zip, and Mail
-
Section 31: Modern PHP Frameworks Deep Dive
-
Section 32: PHP Design Patterns
-
Section 33: More Practice Exercises
-
Section 34: PHP Performance and Deployment
-
Section 35: More Interview Practice
-
Section 36: More PHP Standard Library
-
Section 37: PHP Concurrency and Async
-
Section 38: More Web Development Practice
-
Section 39: PHP Testing Deep Dive
-
Section 40: Composer and Package Development
-
Section 41: PHP Security Deep Dive
-
Section 42: More Practical Projects
-
Section 43: Legacy PHP Maintenance
-
Section 44: More Algorithm Practice
-
Section 45: Final Practice and Review
-
Section 46: PHP for E-Commerce Patterns
-
Section 47: PHP API Design Deep Dive
-
Section 48: PHP Caching Strategies
-
Section 49: PHP Queue and Background Jobs
-
Section 50: PHP Multi-Tenancy Patterns
-
Section 51: PHP Real-Time Features
-
Section 52: PHP CMS and Content Modeling
-
Section 53: PHP Internationalization
-
Section 54: More Framework-Specific Practice
-
Section 55: PHP Legacy Code Refactoring
-
Section 56: More Practice Projects Round 2
-
Section 57: PHP Command-Line Applications
-
Section 58: PHP and Microservices
-
Section 59: More Interview and Review Round 2
29: Named Arguments and Constructor Promotion
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
Productclass to use Constructor Property Promotion. - The class should have the following properties:
string $name,float $price,int $stock = 0, andbool $isDigital = false. - Below the class, instantiate a new
Productobject using Named Arguments. - The product should be named "Mechanical Keyboard", cost 129.99, and be marked as
isDigital = false, but you should omit thestockargument entirely to let it use its default value.
<?php
// Your code here
?>There are no comments for now.