Tell the iterator of strict type objects in PHPDoc

Features

  • I am using the PHPStorm 8 IDE.
  • Suppose we have a class Foo that implements the \Iterator interface, and we know that all elements inside this iterator will be an instance of the Bar class.

Question

How to hint that Foo is iterable and contains only Bar elements? Of course, the prompt should contain information that the instance of Foo

What have i tried so far

If we had an array of Bar instances, then this is not an easy thing (this, for example, describes this question): Bar[] . Also, if the goal is to iterate through Foo , it can still 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 that is not achievable with a hint of place: the type of return. If I have some method that should return Foo , I only know how to hint that Foo , but the user of this function will still not be able to expose that it is really iterable and contains instances of Bar (for example, as if I pointed out @return Bar[] in the case of an array of Bar instances)

+5
source share
1 answer

If Foo implements Iterator , then you can specify the return type to Foo::current() . PHPStorm will recognize that it returns a Foo::current() value when you foreach more than Foo .

For instance:

 <?php class Foo implements Iterator { // ... /** * @return Bar */ public function current() { // ... } // ... } $foo = new Foo(); foreach ($foo as $object) { // PHPStorm will recognise $object is type Bar. } 
+3
source

Source: https://habr.com/ru/post/1208277/


All Articles