Leto Casonic
Leto Casonic

Reputation: 43

How often will a function be called when it seems te be used twice in a PHP ternary operation?

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

Answers (1)

AbraCadaver
AbraCadaver

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

Related Questions