0

Let's say I have an object called MyObject and I have an array called $array. Can I typecast this $array var to be of type "array of MyObjects"? Something like:

([MyObject])$array;
Tony Friz
  • 883
  • 1
  • 10
  • 27

1 Answers1

1

This is not possible in PHP. The only thing you can do is using some sort of collection, which only takes a specific object. The Standard PHP Library (SPL) brings the SplObjectStorage class, which behaves like a collection of objects. Instead of using arrays, which are bad in memory consumption, you can use the SplObjectStorage like in the following example.

class MyObjectStorage extends SplObjectStorage
{
    public function attach(object $object, $data = null): void
    {
        if (!$object instanceof MyObject) {
            throw new InvalidArgumentException(sprintf(
                'This collection takes MyObject instances only. %s given',
                get_class($object)
            ));
        }

        parent::attach($object, $data);
    }
}

This makes typehinting easier.

class Bar
{
    protected MyObjectCollection $collection;

    public function __construct()
    {
        $this->collection = new MyObjectCollection();
    }

    public function addItem(MyObject $item): void
    {
        $this->collection->attach($item);
    }

    public function getCollection(): MyObjectCollection
    {
        return $this->collection;
    }
}
Marcel
  • 4,854
  • 1
  • 14
  • 24