Using an Array Object

In recent PHP updates, they have added to various interfaces to allow the object to be processed as an array, such as ArrayAccess, Iterator, Countable, etc.

My question is whether it makes sense that the following should work:

function useArray(array $array) { print_r($array); } useArray(new ArrayObj(array(1,2,3,4,5)); 

As of now, PHP throws a hint type error because $array not technically an array. However, it implements all interfaces, which makes it basically identical to an array.

 echo $array[0]; // 1 $array[0] = 2; echo $array[0]; // 2 

Logically, an object should be able to be used wherever an array can be used, since it implements the same interface as the array.

Am I confused in my logic or does it make sense that if an object implements the same interface as an array, should it be accessible in all the same places?

+4
source share
2 answers

Am I confused in my logic or did it make sense that if an object implements the same interface as an array, should it be able to be used in all the same places?

An array is a special type of PHP variable, not an object, so it does not implement any interfaces. ArrayObject is a fully functional object that implements numerous interfaces ( Countable , ArrayAccess , etc.) and allows the object to act as an array in certain cases (for example, in a foreach loop). Therefore, although they do not implement the same interfaces, they sometimes behave the same.

Ideal for PHP to support multiple function signatures:

 function useArray(array $array) { } function useArray(ArrayObject $array) { } 

But until we get it (if we ever get it), you just need to check the types of variables outside the function definition:

 function useArray($array) { if (is_array($array) || $array instanceof ArrayObject) { // Do some stuff } else { throw new Exception('I require an array or an array-like structure!'); } } 

Or try making array -type with the $array argument and handle any warnings / errors that useArray may generate.

+4
source

Your hinting type points to its array type, but your transition to ArrayObj

 function useArray(array $array) ... useArray(new ArrayObj 

So yes, he is going to complain.

Am I confused in my logic or did it make sense that if an object implements the same interface as an array, should it be able to be used in all the same places?

If an object implements the same interface as another class, yes, you can use them interchangeably, but it is still valid for the compiler to complain about your hinting type, since its not the same type.

Just because two objects implement the same interface does not mean that they are of the same type.

0
source

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


All Articles