← All posts

Upgrading from PHP 7.4 to PHP 8: the errors that break your code and how to catch them first

TypeErrors on count(), comparisons that quietly change result, removed functions and waves of deprecations: how to find the incompatibilities in an old PHP project before it reaches production, and how to fix them.

Upgrading from PHP 7.4 to PHP 8: the errors that break your code and how to catch them first

Key points

  • PHP 8 turns many situations that PHP 7.4 tolerated with a warning into fatal errors, and that’s where most projects break.
  • You find incompatibilities before production: lint and run the tests with the target interpreter in Docker, then add static analysis.
  • Composer dependencies often block the upgrade more than your own code does, so check them first.

PHP 7.4 reached end of life at the end of 2022, yet we still take over applications and websites running on it. Often a first attempt went wrong: the host switched versions, a blank page appeared, everyone rolled back. PHP 8 itself isn’t the problem. Upgrading blind is. Here’s the process we use to move a PHP 7.4 codebase to a current version without nasty surprises, along with the errors we find in nearly every project.

Why code that used to work breaks on PHP 8

PHP 8.0 tightened the language: many situations that used to produce a quiet warning now throw a TypeError or ValueError. Code that “worked” by ignoring those warnings simply stops.

Later releases continued in the same direction with deprecations: in 8.1, passing null to a built-in function that expects a string; in 8.2, creating object properties without declaring them. A deprecation breaks nothing today, but it signals a future hard error.

Should you step through 8.0, 8.1, then 8.2? On our projects, no: we go straight to a recent, supported version. Intermediate hops multiply testing without reducing the fixes.

Finding the problems before production does

Golden rule: never discover an incompatibility on the live server. You don’t even need the new PHP locally; the official Docker image does the job:

# Check the whole project's syntax with the target interpreter, without installing it
docker run --rm -v "$PWD":/app -w /app php:8.3-cli 
  sh -c 'find src -name "*.php" -print0 | xargs -0 -n1 php -l | grep -v "No syntax errors"'

# Run the test suite under PHP 8.3
docker run --rm -v "$PWD":/app -w /app php:8.3-cli vendor/bin/phpunit

Linting only catches syntax, such as curly-brace string offsets ($str{0}), removed in 8.0. Everything else shows up at runtime: if the project has no tests, write some around the critical paths before upgrading (basket, invoices, imports).

For code your tests don’t reach, PHPStan can analyse the project for the target version and flag removed functions, type mismatches and deprecations:

# phpstan.neon : analyse the code as if it ran on PHP 8.3
parameters:
    level: 5
    phpVersion: 80300
    paths:
        - src

Start at a low level: the maximum level would bury the real upgrade issues. Rector can apply some fixes automatically; review every change as you would a pull request.

The errors we find in almost every project

These are the cases we fix most often, each with a version that runs on both PHP 7.4 and PHP 8:

<?php
// 1. count() on something that isn't an array: warning in 7.4, TypeError in 8.0
$rows = $stmt->fetchAll() ?: null;
$total = count($rows);                                     // fatal on PHP 8
$total = is_countable($rows) ? count($rows) : 0;         // fixed

// 2. Loose number-to-string comparison: the result has changed
var_dump(0 == 'abc');                     // PHP 7.4 : true  / PHP 8 : false
var_dump(in_array(0, ['abc', 'def']));    // PHP 7.4 : true  / PHP 8 : false
in_array($id, $ids, true);                // compare strictly, no ambiguity

// 3. null passed to a built-in function: deprecated since 8.1
$title = trim($_POST['title']);                              // Deprecated if missing
$title = trim($_POST['title'] ?? '');                        // fixed

// 4. Functions removed in 8.0
while (list($key, $val) = each($options)) { /* ... */ }     // each() no longer exists
foreach ($options as $key => $val) { /* ... */ }            // fixed

// 5. Unparenthesised nested ternaries: fatal error in 8.0
$label = $a ? 'A' : $b ? 'B' : 'C';                       // no longer compiles
$label = $a ? 'A' : ($b ? 'B' : 'C');                     // fixed

The second case is the most dangerous because it raises no error: the result just changes. Look for loose comparisons (==, in_array() and array_search() without the third argument, switch) on values coming from forms or the database. On one project, a permission check depended on the old behaviour without anyone realising.

Classes bring two more issues. Classes implementing built-in interfaces (ArrayAccess, Iterator, Countable, JsonSerializable) need to declare return types as of PHP 8.1. And properties created on the fly have been deprecated since PHP 8.2:

<?php
class Collection implements ArrayAccess, Countable
{
    private array $items = [];

    // PHP 8.1: “Return type ... should either be compatible” when the type is missing
    public function offsetGet(mixed $offset): mixed { return $this->items[$offset] ?? null; }
    public function offsetExists(mixed $offset): bool { return isset($this->items[$offset]); }
    public function offsetSet(mixed $offset, mixed $value): void { $this->items[$offset] = $value; }
    public function offsetUnset(mixed $offset): void { unset($this->items[$offset]); }
    public function count(): int { return count($this->items); }
}

// PHP 8.2: properties created on the fly are deprecated. Declare them.
class Order
{
    public ?string $note = null;   // before: $order->note = '...' with no declaration
}

One last trap: on PHP 8, curl_init() returns a CurlHandle object, not a resource, so is_resource($ch) returns false. GD changed the same way. Check $ch !== false instead.

Composer dependencies and PHP extensions

In practice, it’s often a library rather than your own code that blocks the upgrade: an old framework release or API client that declares support for PHP 7 only. Composer can tell you exactly which one:

# Which packages block the move to PHP 8.3?
composer why-not php 8.3

# Resolve dependencies for the production version, not the one on your laptop
composer config platform.php 8.3.0
composer update --dry-run

The platform.php setting matters. Without it, Composer resolves versions against whatever PHP runs the command, so a developer on PHP 8.4 can install packages that won’t run on the server’s PHP 8.3. Pin it to the production version and commit the resulting composer.lock.

For each blocking package: upgrade (read its upgrade guide), switch to a maintained alternative, or as a last resort vendor and fix it yourself. Also compare extensions with php -m on the old and new servers.

Switching production over safely

Once the tests pass, treat the switch as a release in its own right. We always follow these steps:

  • Run a staging copy on the new version for a few days, with the key user journeys tested by hand.
  • Configure production to log every error without displaying any: error_reporting = E_ALL, display_errors = Off, log_errors = On.
  • Make sure the old PHP version stays available on the server: with most hosts and with PHP-FPM, rolling back takes a minute as long as the old version hasn’t been removed.
  • Remember the command line: scheduled jobs (cron) and queue workers often use a different PHP binary from the web server, and can stay on the old version without anyone noticing.
  • Watch the error log for the following hours, filtering for Fatal, Warning and Deprecated lines.

Deal with remaining deprecations over the following weeks: they’re the next upgrade’s errors. And add the target version to your CI.

FAQ

My WordPress site runs on PHP 7.4. Is it the same job?

The principle is the same, but the code to check is mostly the theme and plugins. Update everything first, then test a copy of the site on the new PHP version. Plugins abandoned by their authors are usually the ones that cause trouble and need replacing.

Can I hide the deprecation notices to move faster?

Keep them off the screen, and you should never display errors in production anyway. But keep them in the logs: today’s deprecation is the next version’s fatal error. Silencing them entirely just sets up the next outage.

Is your application or website still running on an unsupported PHP version? We audit the code, upgrade the dependencies and handle the switch to a current version with no downtime.

Share LinkedIn Facebook X WhatsApp
</>

webtestudio

Web agency: custom WordPress sites, premium themes and SaaS software.

Discuss your project →