How to detect if object is Traversable in PHP?

荒凉一梦 提交于 2019-12-05 17:22:38

问题


How can I detect the variable is a Traversable object to use in foreach loops?

if(is_traversable($variable)) {
    return (array) $variable;
}

回答1:


Use instanceof to determine if the object is Traversable

if($variable instanceof \Traversable) {
  // is Traversable
}



回答2:


is_iterable can be used since PHP 7.1.

// https://wiki.php.net/rfc/iterable
var_dump(
    true === is_iterable([1, 2, 3]),
    true === is_iterable(new ArrayIterator([1, 2, 3])),
    true === is_iterable((function () { yield 1; })())
);


来源:https://stackoverflow.com/questions/31701517/how-to-detect-if-object-is-traversable-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!