1

How to replace this :

if( $this->getInfo() ){ $value = $this->getInfo(); }else{ $value = $this->getAnotherInfo(); } 

This would be nicer solution :

$value = $this->getInfo() ? $this->getInfo() : $this->getAnotherInfo(); 

But we repeat $this->getInfo().

3
  • first, assign the result of $this->getInfo() to the variable, then work with this variable. Otherwise you can't escape double calling of this method. Commented May 24, 2014 at 16:25
  • 1
    possible duplicate of ?: operator PHP Commented May 24, 2014 at 16:28
  • But in this expr $var = fn() ? : 1; fn() called once. Tested. Commented May 24, 2014 at 16:43

3 Answers 3

1

Here is the fun:

$value = $this->getInfo() ? : $this->getAnotherInfo(); 
Sign up to request clarification or add additional context in comments.

3 Comments

Did you correctly answer your own question? Looks like a syntax error to me.
@Popnoodles: No, that's valid syntax. It's called the shorthand ternary syntax. See the documentation: "Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.".
Ok thanks, I've never seen it before. So he answered his own question.
0

If it bothers you having to repeat the expression you could write a function that returns the first truthy value.

$value = which ($this->getInfo(), $this->getAnotherInfo()); function which () { if (func_num_args()<1) return false; foreach (func_get_args() as $s) if ($s) return $s; return false; } 

Comments

0

A nasty option would be this:

if (!($value = $this->getInfo())) $value = $this->getOtherInfo(); 

If the assignment returns false assign the other value.

But aside from this looking disgusting, it is still repetitive, albeit in a different way.


As of PHP 5.3, you can leave out the middle part of the ternary operator and avoid the repetition:

$value = $this->getInfo() ? : $this->getOtherInfo(); 

Which does what you want.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.