Jac*_*ero 5 php instanceof symfony doctrine-orm
通常,您可以使用以下命令检查变量是否是类的实例:
$foo instanceof bar
Run Code Online (Sandbox Code Playgroud)
但是在ArrayObjects(属于Symfony 2)的情况下,这似乎不起作用
get_class($foo) 回报 'Doctrine\Common\Collections\ArrayCollection'
然而
$foo instanceof ArrayCollection
Run Code Online (Sandbox Code Playgroud)
回报 false
is_array($foo)返回false并$is_object($foo)返回true
但我想对这种类型进行具体检查
Flo*_*lus 13
要在命名空间下执行对象的内省,仍然需要使用该use指令包含该类.
use Doctrine\Common\Collections\ArrayCollection;
if ($foo instanceof ArrayCollection) {
}
Run Code Online (Sandbox Code Playgroud)
要么
if ($foo instanceof \Doctrine\Common\Collections\ArrayCollection) {
}
Run Code Online (Sandbox Code Playgroud)
关于您尝试确定用作数组的对象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)) {
}
Run Code Online (Sandbox Code Playgroud)
在ArrayCollection类实现这两个接口.
| 归档时间: |
|
| 查看次数: |
4439 次 |
| 最近记录: |