Reputation: 43
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.
Upvotes: 2
Views: 140
Reputation: 78994
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.
Upvotes: 1