· hutor.tech
How to migrate from PHP 7 to PHP 8
A PHP 8 migration is rarely dramatic, but it is never automatic. Most of the work is finding the handful of places where the language stopped forgiving sloppy code, and the rest is verifying that your dependencies came along for the ride.
Start with the dependencies, not with your own code. Run `composer why-not php 8.2` (or the version you target) and you will get the list of packages that block the upgrade. Update them first, on PHP 7, in separate commits. A migration that changes the runtime and twenty packages at once is impossible to bisect when something breaks.
Then let a static analyser find the real incompatibilities. PHPCompatibility for PHP_CodeSniffer, or Rector with the PHP 8 rule sets, will point at the patterns that changed:
— `match` and `enum` became reserved words;
— string-to-number comparisons follow saner rules, so `0 == "foo"` is now false;
— passing null to non-nullable internal function parameters is deprecated;
— `create_function`, `each` and the `mysql_*` family are gone for good;
— many notices became warnings, and warnings became errors.
The comparison change is the one that bites in production. Code that quietly relied on `"abc" == 0` being true will now take a different branch, and no error is raised. Grep for loose comparisons around user input, identifiers and status codes, and add tests before you change the runtime rather than after.
Do the switch on a staging server that mirrors production: same extensions, same PHP-FPM pool settings, same OPcache configuration. Turn on error reporting, run the application, and read the log rather than the screen — most PHP 8 problems arrive as deprecations long before they arrive as failures.
Once you are on 8.x, spend a day collecting the benefits: constructor property promotion, named arguments, `match`, nullsafe operators and, more importantly, the JIT-free but genuinely faster engine. Do not rewrite everything — apply the new syntax where you are already touching the code, or you will turn a migration into a rewrite and lose the ability to roll back.
Keep a rollback plan until the first quiet week has passed: the previous PHP version installed alongside, the ability to point the pool back, and a database that has not been changed in a way the old code cannot read.