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().

Amal Murali
  • 75,622
  • 18
  • 128
  • 150
jody_lognoul
  • 817
  • 7
  • 15

3 Answers3

1

Here is the fun:

$value = $this->getInfo() ? : $this->getAnotherInfo();
Giacomo1968
  • 25,759
  • 11
  • 71
  • 103
jody_lognoul
  • 817
  • 7
  • 15
  • Did you correctly answer your own question? Looks like a syntax error to me. – Popnoodles May 24 '14 at 16:07
  • 2
    @Popnoodles: No, that's valid syntax. It's called the shorthand ternary syntax. See the [documentation](http://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary): "*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.*". – Amal Murali May 24 '14 at 16:13
  • Ok thanks, I've never seen it before. So he answered his own question. – Popnoodles May 24 '14 at 16:13
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;
}
Popnoodles
  • 28,090
  • 2
  • 45
  • 53
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.

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141