Migrating to PHP 8
How to move a website from PHP 7.4 to PHP 8 – preparation and procedure, changes that break old code, and new features of PHP 8.0 to 8.5: named arguments, the ?-> operator, match, types, constructor property promotion, readonly, enumerations and attributes. The examples are verified in PHP 7.4 and 8.2 to 8.5.
PHP 7.4 no longer receives even security fixes. How to prepare for the move to PHP 8, in which order to proceed and how to write code that runs in both the old and the new version.
Most old code runs in PHP 8 without changes. Some changes, however, silently change the result or end the script instead of issuing a warning. Which ones they are and how to fix the code.
PHP 8.0 brought named arguments, thanks to which there is no need to write out default values, and the ?-> operator, which shortens checks for null. Plus details such as throw in an expression or catch without a variable.
The match expression from PHP 8.0 returns a value, compares strictly and never forgets a break. When to use it instead of switch, how to write ranges with match(true) and what happens when no arm matches.
PHP 8 greatly extended the types of parameters, return values and properties: union types, mixed, never, intersections and constant types. An overview by version with examples and with what declare(strict_types=1) enforces.
Classes in PHP 8 are shorter and safer to write: properties can be declared right in the constructor, readonly prevents them from changing and PHP 8.4 added asymmetric visibility and property hooks.
The enumeration (enum) from PHP 8.1 replaces constants for statuses, roles or types. How to write a pure and a backed enum, convert a value from the database, add methods and use an enum in match.
Attributes from PHP 8.0 replace annotations in comments and built-in attributes reveal errors right when the code runs. Plus an overview of other new features of versions 8.1 to 8.5 – from the short callable syntax to the |> operator.