Forgive me if the title doesn’t exactly match what I’m asking, I’m having a tough time describing the question exactly.
Consider the following PHP code:
#!/usr/bin/php
<?php
class foo{
function bar()
{
return true;
}
}
if (true && $a = new foo() && $a->bar()) {
echo "true";
} else {
echo "false";
}
It gives
Fatal error: Call to a member function bar() on a non-object
for the $a->bar(); expression.
Consider the following C code:
int main(void)
{
int i = 0;
if (i += 1 && printf("%d\n", i))
{
printf("Done: %d.\n", i);
}
}
It outputs :
0
Done: 1.
Why is this? Since C and PHP claim to short-circuit these expressions and evaluate left to right, I expect a value set in expressions to the left to be used in expressions to the right. Is there something I’m missing?
Your problem right now is with operator precedence. PHP currently evaluates your PHP statement as such:
In which case
$ais not defined by the time you try calling$a->bar().What you really want is this:
Using brackets in complex conditions will prevent those kinds of errors from happening.
EDIT: Proof