At a Glance
Date Reviewed
Status
Up to date
Language
PHP
Topic
Summary

PHP 8.4 - released at the end of November 2024 - has deprecated implicit nullable types. For many years (since PHP 5.1), types on function arguments could have a default value of null provided even if the type itself was not nullable.

Now with PHP 8.4 this behaviour is deprecated and should be explicitly marked as nullable.

Example

public static function dialogSettings(LayoutParagraphsLayout $layout = NULL) {
}

Fixing it is extremely easy and backwards compatible at least to 8.0 - in most cases, single character - ? - plus docstring updates. For example:

public static function dialogSettings(?LayoutParagraphsLayout $layout = NULL) {
}

Manual fixes are easy, but automatic fixes (or at least checks) are faster.

 

# Automatically Fixing

You can use PHP CodeSniffer's PHP Code Beautifier and Fixer, specifically using a sniff from slevomat/coding-standard SlevomatCodingStandard.TypeHints.NullableTypeForNullDefaultValue.  If so, run phpcbf [path].

Or, you can use PHP Coding Standards Fixer by Symfony. Note, this example includes files for Drupal support, adjust file types as needed for your use case. Need to create a config file such as this (name/location can be whatever you want):

<?php
$finder = \PhpCsFixer\Finder::create()
    ->in(__DIR__)
    ->name('*.engine')
    ->name('*.module')
    ->name('*.profile')
    ->name('*.theme')
    ->name('*.inc')
    ->name('*.php');

$config = new \PhpCsFixer\Config();
$config->setParallelConfig(PhpCsFixer\Runner\Parallel\ParallelConfigFactory::detect());
return $config->setRules([
        'nullable_type_declaration_for_default_null_value' => true,
    ])
    ->setFinder($finder);

and then run fix (or run check if you want to get a report first).

php-cs-fixer fix --config config-file.php [path]