PHP 8 New Features
- Union types
-
Mixed
- Class constructor property promotion
- Class ubiquity
- Named arguments
- PHP match expressions
- Null safe operator
- Catch by type only
-
str_contains
-
str_starts_with
-
str_ends_with
Syntax Changes
1. Union types
Return types and arguments can be of multiple types, separated using the | operator.
2. Mixed
Mixed is a first class type, using the key word mixed
.
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
Using ::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 (Exception)
New Functions
9. str_contains
We generally would use strpos
to find a string within another string in previous versions of PHP. In PHP 8 we can use str_contains
.
10. str_starts_with
PHP 8 introduces str_starts_with
and str_ends_with
to determine if a string starts with or ends with a specific string.
11. str_ends_with
Further Reading
In this article we looked at the key new features of PHP 7, a detailed list of PHP features can be found here.