PHP 8 New Features
- Union types
- Class constructor property promotion
- Class ubiquity
- Named arguments
- PHP match expressions
- Null safe operator
- Catch by type only
1. Union types
Return types and arguments can be of multiple types, separated using the | operator.
Mixed is a first class type, using the key word
3. Class constructor property promotion
Class constructors that have scoped arguments (e.g:
private string: $name) are promoted to class properties. This reduces a lot of boilerplate code.
4. Class ubiquity
::class on objects is now possible.
5. Named arguments
Named arguments are useful when using only a few arugments for a function that accepts many parameters. You no longer have to set the parameters you're not using and you don't have to know the defaults or the order of arguments.
6. PHP match expressions
Match expressions solve many of the shortcomings of
switch case, match expressions use strict comparisons (same type) and don't require a break after each case.
7. Null safe operator
The null safe operator ignores anything to the right of the null safe operator, allowing more succinct code.
8. Catch by type only
We no longer need to declare a variable for the exception
(Exception $e), we can just declare the exception type
We generally would use
strpos to find a string within another string in previous versions of PHP. In PHP 8 we can use
PHP 8 introduces
str_ends_with to determine if a string starts with or ends with a specific string.
In this article we looked at the key new features of PHP 7, a detailed list of PHP features can be found here.