Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hint iterator of strict type entities in PHPDoc

Tags:

php

phpdoc

Specifics

  • I am using PHPStorm 8 IDE.
  • Let's assume we have some class Foo which implements \Iterator interface and we know that all items inside that iterator will be of instance of class Bar.

Question

How to hint that Foo is iterable and contains only items of Bar? Of course, hint should keep information, that it's instance of Foo

What I tried so far

If we had an array of Bar instances, then that is an easy thing (it's described, for instance, in this question): Bar[]. Also, if the intention is to iterate through Foo, it still can be resolved (more or less) with:

//assume that $foo is instance of Foo
//..

/* @var $object Bar */
foreach ($foo as $object) {
}

However, there is one very important thing which is not achievable with in-place hinting: return type. If I'll have some method which should return Foo, I know only how to hint that Foo, but user of that function still won't be able to expose, that it's actually iterable and contains Bar instances (like it would be if I'll specify @return Bar[] in case with array of Bar instances)

like image 201
Alma Do Avatar asked Sep 29 '22 07:09

Alma Do


1 Answers

If Foo implements Iterator then you can hint the return type on Foo::current(). PHPStorm will recognise that what Foo::current() returns is the value when you foreach over Foo.

For example:

<?php

class Foo implements Iterator
{
    // ...

    /**
     * @return Bar
     */
    public function current()
    {
        // ...
    }

    // ...
}

$foo = new Foo();

foreach ($foo as $object) {
    // PHPStorm will recognise $object is type Bar.
}
like image 152
Courtney Miles Avatar answered Oct 02 '22 16:10

Courtney Miles