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;
6
  • Can you please elaborate a bit? What do you expect here, that every subarray of $array becomes an instance of MyObject? Commented Apr 24, 2021 at 21:23
  • Please check stackoverflow.com/questions/34273367/… Commented Apr 24, 2021 at 21:24
  • you can use phpdoc to help your IDE /** @var MyObject[] $array */ Commented Apr 24, 2021 at 21:35
  • @El_Vanja actually I wanted it for documentation purposes. So Sysix's solution works. Commented Apr 24, 2021 at 21:37
  • Ah, I see. I though you wanted to cast it (judging by your title), but you wanted to hint it. Commented Apr 24, 2021 at 21:51

1 Answer 1

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.