iyagi
iyagi

Reputation: 33

Decrement on type null has no effect, this will change in the next major version

This code has worked in previous versions of PHP for years:

function dayOfWeek ($day, $month, $year)
{
    // ...
    if ($month < 3) {
        $month += 10;
        $year--;  // **24 line**
    }
    else {
        $month -= 2;
    }
    // ...
}

However, since upgrading to PHP 8.3 I sometimes get this warning when I call it:

Warning: Decrement on type null has no effect, this will change in the next major version of PHP in /home/gagebu/www/calendar.php on line 24

How should I edit the code to resolve this warning?

Upvotes: -1

Views: 239

Answers (1)

Machavity
Machavity

Reputation: 31614

PHP has long been trying to clean up some of the mess caused by its inherent weak typing, and this is no exception. This was changed per this RFC, which notes something unexpected happens with trying to increment vs decrement null

$x = $y = null;
$x++;
var_dump($x); // 1
$y--;
var_dump($y); // NULL

That's inconsistent behavior. Instead, PHP is going to expect you to pass something numeric in the future.

To fix your code, just add a check for null. I've added the current year, but you can add your own default value

function dayOfWeek ($day, $month, $year)
{
    if($year === null) $year = date('Y');
    if ($month < 3) {
        $month += 10;
        $year--;  // **24 line**
    }
    else {
        $month -= 2;
    }
}

Upvotes: 3

Related Questions