Fix PHP 8.4 deprecation: Implicitly marking parameter as nullable is deprecated, the explicit nullable type must be used instead

RMAG news

PHP 8.4 will be released in November 2024, but the list of new features and deprecated features is already very established. It is clearly detailled on php.watch/versions/8.4.

The most prominent change is the deprecation of implicit nullable parameter declarations:

function test(string $test = null) {}

test(‘PHP’); // Allowed
test(null); // Allowed

which is easy to fix using the explicit nullable type introduced in PHP 7.1:

– function test(string $test = null) {}
+ function test(?string $test = null) {}

You can detect this depreciation in your PHP files using PHP’s built-in linter, but you will need a local installation of PHP 8.4.

php -l src/**/*.php

Now that you know the affected files, you can fix them by hand, or automatically.

Fix your codebase using Rector

Rector is an excellent tool for refactoring and modernizing code. In our case, we will only use the ExplicitNullableParamTypeRector rule.

Install rector:

composer require –dev rector/rector

Copy this minimal configuration in rector.php, at the root of your project. We assume your source files are located in src but you can change it to set the path of all your PHP files.

<?php

return RectorConfigRectorConfig::configure()
->withPaths([__DIR__ . ‘/src’])
->withPhpVersion(RectorValueObjectPhpVersion::PHP_84)
->withRules([
RectorPhp84RectorParamExplicitNullableParamTypeRector::class,
]);

Run rector:

vendor/bin/rector

I hope this quick tutorial has saved you some time. There are hundreds of projects to patch on GitHub, have fun!

Leave a Reply

Your email address will not be published. Required fields are marked *