PHP 闭包在 IF 语句中返回什么? [英] What do PHP closures return in IF statements?

查看:26
本文介绍了PHP 闭包在 IF 语句中返回什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是在 if() 语句中加入一些复杂的逻辑.假设我有一个值数组,如果数组中的所有内容都非零,我将执行一些代码.通常,我可以说,$valid = trueforeach 我的数组,并在找到零时设置 $valid = false.然后我会运行我的代码 if ($valid).或者,我可以将我的循环放入一个函数中,并将该函数放入我的 if() 中.

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.

假设我有这个:

if ($q = function() { return 'foo'; }) {
  echo $q;
}
else {
  echo 'false';
}

我期望 if 得到 'foo',它的计算结果为真.我的闭包提交给 $q 并且语句执行.$q 返回字符串 foo,并打印 'foo'.

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.

相反,我收到错误Object of class Closure could not be convert to string.

所以让我们试试这个:

if (function() { return false; }) {
  echo 'foo';
}
else {
  echo 'true';
}

我原以为我的函数会返回 false 并打印true".相反,'foo' 被打印出来.

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?

推荐答案

function() { return false;} 创建一个 Closure<类型的对象/a>,与new类似,其他class-types,对比如下代码:

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

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

$func 现在是一个对象.每个对象在 if 子句中返回 true.所以

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

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

您可能想要这样做:

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

它将调用闭包对象 $func 并给出它的返回值.

which will invoke the Closure object $func and give it's return value.

这篇关于PHP 闭包在 IF 语句中返回什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆