In PHP, include command line syntax for index access in a custom class

Is there a way to enable this syntax for the classes you write:

$object= new my_array_like_class;
// some code that modifies the contents goes here
// now to access a value by index, I want to enable this array like syntax:
$value= $object[$index];

I know this can be used for arrays, but I'm wondering if there is a way to do this using custom types.

+4
source share
1 answer

As @zerkms noted, this is possible with any class that implements an interface ArrayAccess.

The easiest way is to use a class ArrayObjectthat is native to PHP and already implements an interface ArrayAccessthat can be used on its own:

$object = new ArrayObject;
...
$value= $object[$index];

Or advanced:

class MyArrayLikeClass extends ArrayObject {
    ...
}

$object = new MyArrayLikeClass;
...
$value= $object[$index];

ArrayObject - ArrayAccess , IteratorAggregate, (.. foreach).

+2

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


All Articles