Search code examples
phpstorm

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


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?


Solution

  • 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