Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if something is an instance of ArrayCollection

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

like image 945
RonnyKnoxville Avatar asked Nov 13 '14 14:11

RonnyKnoxville


1 Answers

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.

like image 101
Flosculus Avatar answered Nov 12 '22 04:11

Flosculus