1

When I use a ternary operation in PHP like this:

$dataObject = $this->someInstance->getDataFromDB(); //getDataFromDB() for example returns an object or false. It gets data from a database ;-)
$variable = !$dataObject ? false : $dataVariable;

Then getDataFromDB() is called once.

But how often is it called and how often will data from a DB be fetched, when I use the ternary operation like this:

$variable = !$this->someInstance->getDataFromDB() ? false : $this->someInstance->getDataFromDB();

I would prefer the first version when it performs better.

Thanks for your answers.

  • If you do it way number two it is called twice because you're not storing results and in certain cases it might be possible to get two different sets of results depending on what is returned from `getDataFromDB()` You're only testing for truthiness. – Jay Blanchard Mar 05 '20 at 20:10
  • You may be interested in the [Elvis operator](https://stackoverflow.com/questions/1993409/operator-the-elvis-operator-in-php) – TiiJ7 Mar 05 '20 at 20:16
  • 1
    If that method already returns an object or false, setting something to its result or false with a ternary seems redundant. I must be missing something. – Don't Panic Mar 05 '20 at 20:30
  • @Don'tPanic Yes, I was thinking the same thing and was hoping it was just an example and didn't want to write a dissertation on it :) – AbraCadaver Mar 06 '20 at 00:24
  • OP Did you give up??? – AbraCadaver Mar 06 '20 at 00:25
  • Thanks a lot for your answers. Yes of course this is just an example-pseudo-code and not the way code should look like ;-) But this is in my opinion the best way to point on the true 'problem'. I just want to understand the mechanics and behaviour in this case. – Leto Casonic Mar 07 '20 at 13:19

1 Answers1

1

In the second example getDataFromDB() may be called twice if the first expression evaluates to false or you could do it like this:

$variable = !($d = $this->someInstance->getDataFromDB()) ? false : $d;

Or possibly:

$variable = $this->someInstance->getDataFromDB() ?: false;

I'm assuming that the two : was a typo.

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87