【问题标题】:Is there a way to test a variable for "isForEachable"有没有办法测试“isForEachable”的变量
【发布时间】:2011-04-05 14:18:01
【问题描述】:

使用 PHP,是否有一种函数/方法/方式来检查变量是否包含可以安全放入 foreach 构造的内容?类似的东西

//the simple case, would probably never use it this bluntly
function foo($things)
{
    if(isForEachable($things))
    {
        foreach($things as $thing)
        {
            $thing->doSomething();
        }
    }
    else
    {
        throw new Exception("Can't foreach over variable");
    }
}

如果您的答案是“设置一个处理程序来捕获 PHP 错误”,您的努力将受到赞赏,但我正在寻找其他东西。

【问题讨论】:

标签: php iterator foreach


【解决方案1】:

PHP 7

最新版本的 PHP 有 is_iterable()iterable 伪类型。


PHP 5

由于 PHP 5+ 中的所有对象和数组都是“foreachable”...

function is_foreachable($var) {
  return is_array($var) || is_object($var);
}

【讨论】:

    【解决方案2】:

    嗯,有点。你可以这样做:

    if (is_array($var) || ($var instanceof Traversable)) {
        //...
    }
    

    但是,这并不能保证foreach 循环会成功。它可能会抛出异常或静默失败。原因是某些可迭代对象,在某些时候,可能没有任何信息可以产生(例如,它们已经被迭代,只对它们进行一次迭代才有意义)。

    Traversable。数组不是对象,因此无法实现这样的接口(它们早于它),但可以在 foreach 循环中遍历它们。

    【讨论】:

    • 例如DOMNodeList 也是一个有自己方法的对象,但奇怪的是它的 foreach 兼容和它的 !is_array(...)。
    • 请注意,对象也是可访问的,因此您可能希望将|| is_object($var) 添加到条件中。
    【解决方案3】:

    使用is_array检查

    if( is_array($things) )
          echo "it is foreachable";
    else
          echo "Not it's not foreachable.";
    

    【讨论】:

    • foreach 循环支持的不仅仅是数组。
    • 感谢您解决这个问题。抱歉,我的错。我不怎么用 PHP OOP。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-16
    • 1970-01-01
    • 2023-02-18
    • 2015-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多