如何检查是否变量是数组?......什么的阵列状 [英] How to check if variable is array?... or something array-like
问题描述
我想使用的foreach
循环使用一个变量,但是这个变量可以有许多不同的类型, NULL
例如。
I want to use a foreach
loop with a variable, but this variable can be many different types, NULL
for example.
所以在的foreach
我测试一下:
if(is_array($var)){
foreach($var as ...
但我意识到,它也可以是一个类实现的Iterator
接口。也许我是个盲人,但如何检查类是否实现了接口?有什么样 is_a
函数或继承
运营商?我发现 class_implements
,我可以使用它,但也许有一些更简单?
But I realized that it can also be a class that implements Iterator
interface. Maybe I am blind but how to check whether the class implements interface? Is there something like is_a
function or inherits
operator? I found class_implements
, I can use it, but maybe there is something simpler?
第二,更重要的是,我想这个功能的存在,就足以检查变量 is_array
或者implements 的Iterator
界面或者我应该测试更多的东西?
And second, more important, I suppose this function exist, would be enough to check if the variable is_array
or "implements Iterator
interface" or should I test for something more?
推荐答案
如果您使用的是的foreach
在函数内部,你期待一个数组或一个的Traversable 对象,你可以键入提示与功能:
If you are using foreach
inside a function and you are expecting an array or a Traversable object you can type hint that function with:
function myFunction(array $a)
function myFunction(Traversable)
如果您不使用的foreach
函数里面,或者你也希望能够获得的你可以简单地使用此结构来检查,如果您可以通过该变量迭代:
If you are not using foreach
inside a function or you are expecting both you can simply use this construct to check if you can iterate over the variable:
if (is_array($a) or ($a instanceof Traversable))
这篇关于如何检查是否变量是数组?......什么的阵列状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!