Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I tell PhpStorm what the return type of a function is going to be?

Tags:

phpstorm

enter image description here

So if I have a function and in the PHPDoc I specify it'll return a SqsProcessResult object, then I call a function to create a new one of those objects but that function's PHPDoc say return type of Object (as it's a generic factory function) PhpStorm throws up an orange warning.

Can I annotate or otherwise tell PhpStorm the return type will be SqsProcessResult?

like image 553
Force Hero Avatar asked Dec 10 '22 12:12

Force Hero


1 Answers

Yes, you can .. but due to the nature of the issue it may not be cleanest/elegant solution (at least that's what others may say).

Few options:


#1. Just suppress this inspection for that line.

  • Place caret in the highlighted area and press Alt + Enter (or get the same menu via "light bulb" icon)
  • Find the most suitable entry .. and press Arrow Right key (or mouse click on the tiny triangle icon) to expand submenu
  • Once there -- choose Suppress for statement option -- a new inline PHPDoc comment will be added just above tat line that instructs PhpStorm to ignore that specific Inspection in the next line.

Will be something like this:

/** @noinspection PhpIncompatibleReturnTypeInspection */
return \Yii::createObject(...);
  • Pros: no warning from IDE side
  • Cons: extra PHPDoc comment to satisfy IDE (which is needed considering the circumstances)

#2. Use some intermediate variable that you can type hint in place.

Add something like this instead of that existing single line:

/** @var SqsProcessResult $res */
$res = \Yii::createObject(...);
return $res;
  • Pros: no suppression comment
  • Cons: extra variable (and still extra PHPDoc comment) for basically no reason

This one mainly can be used in longer methods where such variable (generic Object) will be created in the beginning/middle of the function body and then used later.


#3. Play with .metadata functionality and provide resolution logic for actual \Yii::createObject() (so IDE chooses the right class based on input parameter).

https://confluence.jetbrains.com/display/PhpStorm/PhpStorm+Advanced+Metadata

This is how quite a few tools working: IDE helper for Laravel, Symfony helpers, DI Container helpers etc

like image 130
LazyOne Avatar answered Jan 13 '23 10:01

LazyOne