My goal is to put some complex logic in an if() statement. Let's say I have an array of values and I'm going to execute a bit of code if everything in my array is nonzero. Normally, I could say, $valid = true
, foreach
my array, and set $valid = false
when a zero is found. Then I'd run my code if ($valid)
. Alternatively, I could put my loop into a function and put the function intop my if()
.
But I'm lazy, so I'd rather not muck about with a bunch of "valid" flags, and I'd rather not write a whole new function that's only being used in one place.
So let's say I have this:
if ($q = function() { return 'foo'; }) {
echo $q;
}
else {
echo 'false';
}
I was expecting that the if
gets 'foo'
, which evaluates to true. My closure is committed to $q
and the statement executes. $q
returns string foo
, and 'foo' is printed.
Instead, I get the error Object of class Closure could not be converted to string
.
So let's try this instead:
if (function() { return false; }) {
echo 'foo';
}
else {
echo 'true';
}
I was expecting that my function would return false and 'true' would be printed. Instead, 'foo' is printed.
What is wrong about the way that I'm going about this? It seems like it's saying, "Yep, that sure is a function!" instead of "No, because the function evaluated to false." Is there a way to do what I'm trying to do?