This isn't possible. array()
is not an object of any class. Hence, it can't implement any
interface (see here). So you can't use an object and an array interchangeably. The solution strongly depends on what you'd like to achieve.
Why don't you change the function signature to allow only ArrayObject
s, ArrayIterator
s, ArrayAccess
s, IteratorAggregate
s, Iterator
s or Traversable
s (depending on what you'd like to do inside the function)?
If you have to rely on interation-capabilities of the passed object you should use Traversable
as the type-hint. This will ensure that the object can be used with foreach()
. If you need array-like key-access to the object (e.g. $test['test']
) you should use ArrayAccess
as the type-hint. But if you need the passed object to be of a specific custom type, use the custom type as the type-hint.
Another option would be to not use a type-hint at all and determine the type of the passed argument within the function body and process the argument accordingly (or throw an InvalidArgumentException
or something like that).
if (is_array($arg)) { ... }
else if ($arg instanceof Traversable) { ... }
else if ($arg instanceof ArrayAccess) { ... }
else {
throw new InvalidArgumentException('...');
}