In PHP it is possible to specify argument types although they call it type hinting.
I am implementing an interface where one of the functions specifies an array as the argument type:
function myFunction(array $argument){
}
I'd like to define a class, an instance of which can be used as the argument for this function. In other words it would extend ArrayObject or implement ArrayAccess or something along those lines.
Is there a built in interface or abstract class that will work for this? (ArrayObject doesn't)
There isn't, but I'd suggest two alternatives:
Example for soulmerge :-)
function myFunction(array $argument){
echo var_export($argument,true);
}
$a = new ArrayObject();
$a[] = 'hello';
$a[] = 'and goodbye';
myFunction((array)$a);
outputs
array (
0 => 'hello',
1 => 'and goodbye',
)
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('...');
}
No, this is not possible, as array is a primitive type in PHP. An instance of a class is an object, and the PHP-internal comparison already stops at this point (Interfaces and the like are not checked).
You could create an array out of your object:
$array = array();
foreach ($yourObject as $key => $value) {
$array[$key] = $value;
}