Usually you it is possible to check whether a variable is an instance of a class by using:
$foo instanceof bar
But in the case of ArrayObjects (belonging to Symfony 2), this does not seem to work
get_class($foo)
returns 'Doctrine\Common\Collections\ArrayCollection'
yet
$foo instanceof ArrayCollection
returns false
is_array($foo)
returns false
and $is_object($foo)
returns true
but I would like to do a specific check on this type
To perform introspection of an object under a namespace, the class still needs to be included using the use
directive.
use Doctrine\Common\Collections\ArrayCollection;
if ($foo instanceof ArrayCollection) {
}
or
if ($foo instanceof \Doctrine\Common\Collections\ArrayCollection) {
}
Regarding your attempt to determine the objects use as an array with is_array($foo)
.
The function will only work on the array
type. However to check if it can be used as an array, you can use:
/*
* 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)) {
}
The ArrayCollection
class implements both of these interfaces.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With