Null Coalescing Operator equivalent for object property


I’m currently following through the PHP Novice to Ninja book, and adapting it for a blog website. I have potential problem if a user account is deleted and I’m wondering how I might do the equivalent of a null coalescecing operator on the following name property of a comment object:

<?php echo htmlspecialchars($comment->getAuthor()->email, ENT_QUOTES, 'UTF-8') ; ?>

Something like:

<?php echo htmlspecialchars($comment->getAuthor()->email, ENT_QUOTES, 'UTF-8') ?? 'deleted user' ; ?>

The null coalescing operator will not work on the output of htmlspecialchars(), because htmlspecialchars() always returns a string - in case of null input it will output an empty string. You have to use it on the value which can be null. Supposing $comment->getAuthor()->email can be null you can do this:

echo htmlspecialchars($comment->getAuthor()->email ?? 'deleted user', ENT_QUOTES, 'UTF-8'); 

I’m guessing $comment->getAuthor() returns null for a deleted user? In that case it should be something like

$author = $comment->getAuthor();
echo htmlspecialchars($author ? $author->email : 'deleted user', ENT_QUOTES, 'UTF-8'); 

Or, if you’re on PHP8 you can use the null-safe operator (?->)

echo htmlspecialchars($comment->getAuthor()?->email ?? 'deleted user', ENT_QUOTES, 'UTF-8'); 

Works a treat. Thanks

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.