- Nullsafe Operator (?->) ✅ Purpose: Safely access a property/method only if the object is not null.
// Without nullsafe
$name = $user && $user->profile ? $user->profile->name : null;
// With nullsafe
$name = $user?->profile?->name;
✅ Use it to simplify deep object access that might be null.
- Named Arguments ✅ Purpose: Call functions using argument names instead of relying on order.
Named arguments were introduced in PHP 8.0, released on November 26, 2020.
✅ Key Details:
You can pass arguments by name instead of position.
Order doesn't matter, as long as required arguments are passed.
Great for optional parameters and readability.
🚫 Named arguments cannot be used with functions that use func_get_args(), as that relies on position.
function sendMail($to, $subject, $message) {}
sendMail(
to: 'user@example.com',
message: 'Hello!',
subject: 'Welcome' // ✅ Order doesn’t matter!
);
e.g :
function createUser(string $name, int $age, string $role = 'user') {
return "$name is $age and has role $role";
}
echo createUser(age: 25, name: 'Raza', role: 'admin');
✅ Great for readability, especially with many optional parameters.
- Constructor Property Promotion ✅ Purpose: Auto-declare and assign class properties from the constructor.
old way : before php 8.0
class Product {
public string $name;
public int $price;
public function __construct(string $name, int $price) {
$this->name = $name;
$this->price = $price;
}
}
new way: not support for previos versions of php before 8.0
class Product {
public function __construct(
public string $name,
public int $price
) {}
}
🧠 Benefits:
Less code to write and maintain.
Makes class definitions cleaner and easier to read.
Supports visibility modifiers (public, protected, private) and default values.
🔍 Notes:
Only available inside the constructor.
Works with typed properties (which were introduced in PHP 7.4).
Promoted properties must have a visibility modifier (public, private, or protected).
Top comments (0)