2

In any "sane" programming language, from C to Javascript, an expression such as a || b (or a or b) evaluates to a if a is true and to b otherwise, making possible things like a = params.a || default_a and similar for the and operator, but PHP begs to differ.

Is there any way to get this in PHP? Or is there any "coding idiom/pattern" that PHP programmers use instead of something like the code below?

$a = $my_a || $default_a; // nope, $a gets a boolean

Because writing if ($my_a) $a = $my_a; else $a = $default_a; or $a = $my_a ? $my_a : $default_a; seems very ugly to me and violates basic "DRY-ness" of code by making me repeat something like $my_a, which can also be a very long and complicated expression.

It's a minor thing, I know, and not that singular in the land of the double clawed hammer but it really annoys the hell outta me!

4

1 回答 1

0

值得一提的是:C 和 Javascript 有所不同,因为“在“理智”语言中”(;)) 布尔运算的返回值是布尔值,而不是其操作数之一。

然而

$a = $my_a ?: $default_a;
于 2012-07-03T13:04:05.767 回答