-2

I have just had a wordpress template fail giving E_PARSE errors on a number of lines with the following syntax:

$thumbnail_size = $post->image_size ?? 'medium';

I am not familiar with the ?? operator so replaced the lines with this:

$thumbnail_size = $post->image_size ? $post->image_size : 'medium';
  1. Is this an equivalent statement?
  2. Is there any reason why ?? should fail? (PHP Version 5.6.40, Wordpress 6.1.1)

The original code was working 3 days ago. Wordpress version hasn't changed and PHP Info doesn't suggest the PHP version has changed for over 6 months.

MattP
  • 2,798
  • 2
  • 31
  • 42
  • "PHP Version 5.6.40" — Yikes! [5.6 has been out of support for over 4 years!](https://www.php.net/eol.php). Upgrade ASAP. – Quentin Feb 16 '23 at 12:34
  • 1
    `?:` checks for falsyness, `??` for nullness – knittl Feb 16 '23 at 12:34
  • 1
    `??` was added in PHP 7 (which went out of support at the same time as 5.6). – Quentin Feb 16 '23 at 12:35
  • Not sure who fixed the PHP version at that but looks like I can update it to at least 7.2.34 and revert my changes. Not my site/server so I hadn't checked previously. – MattP Feb 16 '23 at 13:01

1 Answers1

-1

The null coalescing operator ?? was introduced in PHP 7.0.

$x = $a ?? $b is equivalent to $x = isset($a) ? $a : $b. If $a is a complex expression (e.g. a function call), it is evaluated only once.

So no, your two statements are not equivalent.

cabrerahector
  • 3,653
  • 4
  • 16
  • 27
knittl
  • 246,190
  • 53
  • 318
  • 364