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 detailed 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. This requires a local installation of PHP 8.4.
php -l src/**/*.php
Now that you know the affected files, you can fix them by yourself, or automatically using PHP-CS-Fixer or Rector.
Fix your codebase using PHP-CS-Fixer
PHP Coding Standards Fixer is a tool to automatically apply formatting rules on your code. In our case, we will use only the nullable_type_declaration_for_default_null_value
rule.
1 - Install php-cs-fixer:
composer require --dev friendsofphp/php-cs-fixer
2 - Copy the minimal configuration in .php-cs-fixer.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
$finder = PhpCsFixer\Finder::create()
->in([__DIR__ . '/src'])
->name('*.php')
return (new PhpCsFixer\Config())
->setFinder($finder)
->setRules([
'nullable_type_declaration_for_default_null_value' => true,
]);
3 - Run php-cs-fixer
vendor/bin/php-cs-fixer fix
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.
1 - Install rector:
composer require --dev rector/rector
2 - 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 Rector\Config\RectorConfig::configure()
->withPaths([__DIR__ . '/src'])
->withPhpVersion(Rector\ValueObject\PhpVersion::PHP_84)
->withRules([
Rector\Php84\Rector\Param\ExplicitNullableParamTypeRector::class,
]);
3 - 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!
Top comments (3)
I have done this myself so many times.
But my fix is now
function test(string $test = '') {}
instead of making the type hinting nullable.Null is an option that should be avoided if you have the choice, in parameters and in returns.
That's very clever. The
null
is often abused.Thank you for your comment.
I love rector, it really speeds up refactoring when new versions come out.
Sometimes the code just needs to be revaluated. It will be more work most of the time. But this will make the code better than only removing the error.