What are the new features of PHP 8?
PHP 8.0 was a big release. It added many features that make code shorter and safer. Here are the main ones that are asked in interviews.
- Named arguments: pass values by parameter name, for example
new User(name: "Robin"). - Constructor property promotion: declare and set properties in the constructor line.
- Match expression: a stricter and shorter version of switch. See PHP match Expression.
- Nullsafe operator (?->): stops the chain if the value is null.
- Union types: a parameter or return can have more than one type, like
int|string. - Attributes: add metadata to classes and methods using the
#[...]syntax. - JIT compiler: can make some heavy calculations faster.
- New functions:
str_contains(),str_starts_with()andstr_ends_with().
<?php
class User {
public function __construct(public string $name, public ?string $city = null) {}
}
$user = new User(name: "Robin"); // named argument
echo $user->name . "<br>";
echo ($user?->city ?? "City not given") . "<br>"; // nullsafe operator
echo str_contains("Tutorials Class", "Class") ? "Found" : "Not found";
?>
Output:
Tutorials Class - Output Window
Robin
City not given
Found
Later versions added more, for example enums and readonly properties in PHP 8.1. Always check the version of PHP on your server before using a new feature.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |