In recent updates to PHP, they added in various interfaces to allow an object to be treated as an array, such as ArrayAccess, Iterator, Countable, etc.
My question is, would it then make sense that the following should work:
function useArray(array $array)
{
print_r($array);
}
useArray(new ArrayObj(array(1,2,3,4,5));
As of right now, PHP throws a type-hinting error, as $array is not technically an array. However, it implements all the interfaces that makes it basically identical to an array.
echo $array[0]; // 1
$array[0] = 2;
echo $array[0]; // 2
Logically, the object should be able to be used anywhere an array can be used, as it implements the same interface as an array.
Am I confused in my logic, or does it makes sense that if an object implements the same interface as an array, it should be able to be used in all the same places?
An
arrayis a special PHP variable type – not an object – as such it doesn’t implement any interfaces.ArrayObjectis a full-fledged object that implements numerous interfaces (Countable,ArrayAccess, etc.) and enables an object to act like an array in certain cases (like in a foreach loop). So while they don’t implement the same interfaces they sometimes behave the same.The ideal solution would be for PHP to support multiple function signatures:
But until we get that (if we ever get that) you’ll just have to check variable types outside the function definition:
Or try to do
array-type stuff with the$arrayargument and handle any warnings/errors thatuseArraymight generate.