0

Firstly I want to create some sort of array that allows only the addition of a certain type of object; MyObject.

Secondly I want this array to be immutable, like a value object array. I want to add MyObjects on creation, access them using a foreach or using offsets $myArray[0] but I don't want items added, removed or sorted - or the items themselves changed.

So I have looked up ArrayObject, ArrayIterator and ArrayAccess. From what I can tell, these allow an object to act as an array. I'm pretty sure that's not what I want but since the PHP array functionality is not actually a class that I can extend, im not sure what path to take.

My current implementation is just a dumbed down class. It cannot be used in a foreach or using array offsets like $myArray[0] without calling the getArray function first.

foreach ($myArray->getArray() as $myObjecy) {

It's the best I can think of but there must be some better way of doing this?

MyCustomArray
{
    protected $array = [];

    public __construct(array $array)
    {
        foreach($array as $obj) {
            if (! $obj instanceof \MyObject) {
                Throw new \Exception();
            }
        }

        $this->array = $array;
    }

    public getArray()
    {
        return $this->array;
    }

    // Stop people dynamically adding properties
    public function __set($name, $value) {
        throw new \Exception();
    }
}
myol
  • 8,857
  • 19
  • 82
  • 143
  • 1
    You should have a look on this lib. https://github.com/jkoudys/immutable.php – Oliver Mar 28 '17 at 11:06
  • [`ArrayAccess`](http://php.net/manual/en/class.arrayaccess.php) gives you the `[]` operator functionality. For `foreach`, you need to implement the [`Traversable` interface](http://php.net/manual/en/class.traversable.php). As far as I can tell, all of that comes with [`ArrayObject`](http://php.net/manual/en/class.arrayobject.php) - did you try using it? – domsson Mar 28 '17 at 11:23

0 Answers0