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

查看:181
本文介绍了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',其值为true.我的闭包将提交给$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 converted 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 与其他类类型的new类似,比较以下代码:

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.
}

您可能要改为执行此操作:

You might want to do this instead:

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

它将调用Closure对象$func并为其提供返回值.

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

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

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