检查某个东西是否是ArrayCollection的实例

6
通常情况下,您可以使用以下方法检查变量是否是类的实例:

$foo instanceof bar

但是在 Symfony 2 的 ArrayObjects(数组对象)中,这似乎不起作用。

get_class($foo) 返回 'Doctrine\Common\Collections\ArrayCollection'

然而,

$foo instanceof ArrayCollection

返回false

is_array($foo)返回falseis_object($foo)返回true

但我想对这种类型进行特定的检查


你是在使用表单吗? - Oliver Bayes-Shelton
是的,我正在一个表单构建器中使用它。 - RonnyKnoxville
1个回答

16

要在命名空间下对对象进行内省,仍需使用use指令将该类包含进来。

use Doctrine\Common\Collections\ArrayCollection;

if ($foo instanceof ArrayCollection) {

}
或者
if ($foo instanceof \Doctrine\Common\Collections\ArrayCollection) {

}

关于您尝试使用is_array($foo)确定对象是否可用作数组。

该函数仅适用于array类型。但是,要检查它是否可以用作数组,您可以使用:

/*
 * If you need to access elements of the array by index or association
 */
if (is_array($foo) || $foo instanceof \ArrayAccess) {

}

/*
 * If you intend to loop over the array
 */
if (is_array($foo) || $foo instanceof \Traversable) {

}

/*
 * For both of the above to access by index and iterate
 */
if (is_array($foo) || ($foo instanceof \ArrayAccess && $foo instanceof \Traversable)) {

}

ArrayCollection 类实现了这两个接口。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接