Specifics
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)
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.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With