问题
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