0

my problem is getting the right type of object from a method, which is returning a "mixed" type due to inhreitance.

I've got a generic list class

class List
{
    /**
    * @var Item[]
    */
    protected $items;

    public function __construct()
    {
        $this->items = array();
    }

    /**
    * @return Item[]
    */
    public function getAll()
    {
        return $this->items;
    }


    /**
    * @return Item
    */
    public function getOne($index)
    {
        if (isset($this->items[$index])) {
            return $this->items[$index];
        }
        return null;
    }
}

containing element of type Item, which is a generic class either

class Item
{
    /**
    * @var string
    */
    protected $name;

    public function __construct($name)
    {
        $this->name = $name;
    }
}

Such generic classes are extended by N different lists. Just an example

class UserList extends List
{
    /* user-specific implementation */
}

class User extends Item
{
    /* user-specific implementation */
}

In the client code

$user_list = new UserList();
foreach ($user_list->getAll() as $user) {
    echo $user->getEmailAddr();
}

Inside the foreach I don't have code completion, because my getAll method (inherited from the father) is returning Item[], or mixed[], not a User[]. Same problem with getOne method. I wouldn't like to have to override such methods.

Is there a more clever and elegant solution? Thank you

Barmar
  • 741,623
  • 53
  • 500
  • 612
Marco
  • 759
  • 3
  • 9
  • 22
  • Most IDEs will provide a way for you to help them by telling it what type is used in the iteration. – PeeHaa Jul 19 '16 at 20:06

1 Answers1

1

I don't think there's any way for the IDE to infer the type automatically. Use a phpdoc type annotation:

foreach ($user_list->getAll() as $user) {
    /** @var User $user */
    echo $user->getEmailAddr();
}

See the related question PHPDoc type hinting for array of objects?

Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612