Verify that something is an instance of ArrayCollection

You can usually check if a variable is an instance of a class using:

$foo instanceof bar 

But in the case of ArrayObjects (owned by Symfony 2) this does not work

get_class($foo) returns 'Doctrine\Common\Collections\ArrayCollection'

till

 $foo instanceof ArrayCollection 

returns false

is_array($foo) returns false and $is_object($foo) returns true

but I would like to perform a specific check of this type

+5
source share
1 answer

To introspect an object in a namespace, the class must still be included using the use directive.

 use Doctrine\Common\Collections\ArrayCollection; if ($foo instanceof ArrayCollection) { } 

or

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

As for your attempt to determine what objects use as an array with is_array($foo) .

The function will work only with 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.

+12
source

Source: https://habr.com/ru/post/1206806/


All Articles