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();
}
}