Skip to main content
  1. About
  2. For Teams
Asked
Viewed 219 times
Part of PHP Collective
2

It works fine and doesn't cause problem

echo $formErrorBag[ 'email' ] ?? null

But is it an accepted practice? Never saw an example of this used with null.

6
  • But why? Can you provide an example of this?
    Jerodev
    –  Jerodev
    2017-02-23 14:23:14 +00:00
    Commented Feb 23, 2017 at 14:23
  • just did so it was escaped.
    Robert Brax
    –  Robert Brax
    2017-02-23 14:23:33 +00:00
    Commented Feb 23, 2017 at 14:23
  • Again, why would you do this? If $formErrorBag['email'] is null this will already return null, you are just adding extra code that will make your application slower.
    Jerodev
    –  Jerodev
    2017-02-23 14:24:16 +00:00
    Commented Feb 23, 2017 at 14:24
  • 2
    It avoids a php warning so it seems useful to me.
    jeroen
    –  jeroen
    2017-02-23 14:24:58 +00:00
    Commented Feb 23, 2017 at 14:24
  • 1
    Won't it crash if $formErrorBag['email'] is not defined ?
    Robert Brax
    –  Robert Brax
    2017-02-23 14:25:03 +00:00
    Commented Feb 23, 2017 at 14:25

2 Answers 2

7

It's completely legal, and accepted. It's a pretty easy and elegant way to avoid raising an E_NOTICE if $formErrorBag doesn't have an 'email' key.

Sign up to request clarification or add additional context in comments.

Comments

1

The null coalesce operator checks values with isset(), so this:

echo $formErrorBag['email'] ?? null;

Equals:

if(isset($formErrorBag['email'])){
  echo $formErrorBag['email'];
} else {
  echo null;
}

I really don't see the point in that as you are still executing a function doing literally nothing. If you are doing this to avoid raising an E_NOTICE you can simply turn it off with error_reporting() as doing your method kinda breaks the entire point of that.

It's there to warn you about a possible bug in your code, not finding techniques to suppress it.

error_reporting(error_reporting() ^ E_NOTICE); // turn notices off keep remaining flags intact.

echo $array['doesnotexist'];
echo $array['etc'];

error_reporting(error_reporting() | E_NOTICE); // turn it back on.

Comments

Your Answer

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Morty Proxy This is a proxified and sanitized view of the page, visit original site.