Inform PHPstorm of return types

I have some methods that return a custom type (for instance, my `getImage()` method returns an `Image` type). When I assign that object to a variable (eg: `$image = $parent->getImage()`) the variable isn't aware of its type (ie, if I now type `$image->`, I don't get any autocomplete options). 

Is there a way to tell PHPstorm the type that a function returns, so I can get the same autocorrect behaviour? Does PHPstorm read PHPdoc blocks? If so, do I need to re-parse the codebase somehow?


Loving PHPstorm, just came over from like ten years of notepad++, what have I been doing with my life?

Comment actions Permalink

Does PHPstorm read PHPdoc blocks?

Yes, absolutely. You can use both @return Image tag for getImage() and @var Image tag for $image for a single occurrence.

For more advances use cases, there's advanced metadata, but PHPDoc alone can do a lot.

Comment actions Permalink

This would be possible using PhpStorm Advanced Metadata:

Not a trivial stuff but once you puzzle this out - you're all set for your project.

Comment actions Permalink

No wayyyyyy that's awesome.

Ok what if I have a factory function that returns a type depending on a given parameter?

I have a `Product` type and a `Restaurant` type in my system, both of which extend the `DomainObject` type, but both of which have their own methods. I realise I could say `@returns DomainObject` and that would get me most of the way there, but it would be nice to have those extra methods in the autocomplete.

So when I call `$obj->getChildrenByType( 'Product' )` I would like to have all those product-specific functions. Would that be a case for your "single occurrence" example? Where do I put that declaration?


Please sign in to leave a comment.