What do PHP closures do in IF statements?

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?

+7
source share
5 answers

function() { return false; } function() { return false; } creates an object of type Closure , similar to new with other types of classes, compare the following code:

 $func = function() { return false; }; 

$func now an object. Each object returns true in the if clause. So

 if ($func) { # true } else { # will never go here. } 

Instead, you can do this:

 if ($func()) { # true } else { # false } 

which will call the Closure $func object and give it a return value.

+4
source

Both of them evaluate true.

You need to make the function execute for use in the if statement.

Try the following:

 $q = function() { return false; }; if ($q()) { //should not go here. echo $q(); } else { echo 'false'; } 

Demo: http://codepad.viper-7.com/Osym1s

+3
source

PHP closures are implemented as hacks of type Closure . Your code actually creates an instance of the object of this class and assigns it $ q. In PHP, the result of an assignment is an assigned value, therefore, in essence, the code boils down to

 if (new Closure()) { ... } 
+2
source

You do not close when you call echo , trying to print a close, not the result of the close:

 echo $q(); 
+1
source

You create an anonymous function but do not execute it. When you test $q = function() { return 'foo'; } $q = function() { return 'foo'; } , you say: "Assign a link to this anonymous function to $ q and pass this test if $ q is not null" (don't like PHP?)

You need to call the closure and assign its result $q before testing and repeating $q .

0
source

All Articles