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 some code if everything in my array is nonzero. Usually I can say $valid = true , foreach my array and set $valid = false when zero is found. Then I would run my if ($valid) code. Alternatively, I could include my loop in a function and put the function in int my if() .
But I'm lazy, so I would rather not guess with a bunch of βrightβ flags, and I would rather not write a whole new function that is used only in one place.
So let's say I have this:
if ($q = function() { return 'foo'; }) { echo $q; } else { echo 'false'; }
I expected if get 'foo' , which evaluates to true. My close is completed $q , and the statement is executed. $q returns the string foo and prints 'foo'.
Instead, I get the error Object of class Closure could not be converted to string .
So try instead:
if (function() { return false; }) { echo 'foo'; } else { echo 'true'; }
I was expecting my function to return false and "true" would be printed. Instead, "foo" is printed.
What is wrong with how I do it? He seems to be saying, βYes, it is definitely a function!β instead of "No, because the function evaluates to false." Is there a way to do what I'm trying to do?
ajp5103
source share