by srn · 17y ago · 0 comments
Extend this to functions as well.
I had a bug like
if (foo(b == A))
instead of
if(foo(b) == A)
Even most bad compilers warn about this now.
puts 'argh' if a = 'b' warning: found = in conditional, should be ==
<?php
if (false !== ($pos = strpos($haystack, $needle))) {
doSomethingWith($haystack, $pos);
}
?>
I find the constant first notation to be very friendly, btw. It's not as natural when translated into English normally, but in terms of logic, it makes sense to think of the first part of the test condition as its own little predicate: // Generic language
bool matchesMyConstantValue(val) {
return MY_CONSTANT_VALUE == val;
}I find assignment-in-conditional more useful in loops than if's, since you can't just plonk the assignment on the previous line.
if ($result = $o->someMethod()) {
// Do Something with $result, the method returned a value that cast to true
}