PHP 8.0 contains new features which include named arguments, union types, attributes, constructor property promotion, match expression, nullsafe operator, JIT, and improvements in the type system, error handling, and consistency. Following is a quick usage of these features.
Named arguments:
htmlspecialchars($string, double_encode: false);
Attributes:
class PostsController
{
#[Route("/api/posts/{id}", methods: ["GET"])]
public function get($id) { /* ... */ }
}
Constructor property promotion:
class Point {
public function __construct(
public float $x = 0.0,
public float $y = 0.0,
public float $z = 0.0,
) {}
}
Union Types:
class Number {
public function __construct(
private int|float $number
) {}
}
new Number('NaN'); // TypeError
Match Expressions:
echo match (8.0) {
'8.0' => "Oh no!",
8.0 => "This is what I expected",
};
//> This is what I expected
Nullsafe operator:
country = $session?->user?->getAddress()?->country;
Saner string to number comparisons:
0 == 'foobar' // false
Consistent type errors for internal functions
strlen([]); // TypeError: strlen(): Argument #1 ($str) must be of type string, array given
array_chunk([], -1); // ValueError: array_chunk(): Argument #2 ($length) must be greater than 0
Which new feature do you feel is the best in this new upgrade?
Comments