Null Coalescing Assignment operator question (php 8.1)

So… hello!

Looking at upgrading some code from 7.4 to 8.1

    $topics = isset($topics) ? $topics : ''; // php7.4, works
// replace with apparently like for like
    $topics ??= ''; // php 8.1.28, throws 'syntax error, unexpected '='

Any idea why the error? Looking at the example in point 4 it appears to be correct syntax?

There’s nothing wrong with the posted code. When code looks okay, but produces errors like this, it is usually caused by copy/pasting things from the web, where they have been ‘published’ and don’t actually contain simple ascii characters. I recommend that you delete and retype everything after the ‘s’ in $topics.

Thank you, tried that and same issue.

What php version are you actually using? Create a .php script with a phpinfo(); statement, and browse to the URL of this file on your web server. At the very top will be the php version.

PHP Version 8.1.28

Also thought it could be a version issue however I replaced

if ((substr( // php 7.4
if ((str_starts_with // php 8.1.28

and no errors flagged with those changes.

Editing is being done via cPanel editor; perhaps there’s an issue with that flagging an error when it doesn’t actually exist.

If you are getting this error from something other than the php language engine, it means nothing.

BTW - this was introduced in php7.4.

Sponsor our Newsletter | Privacy Policy | Terms of Service