How to mark a non-returning function in PhpStorm

php, phpstorm

Solution

If you are using PHP 8.1 or later, you can use the `never` return type:

<?php

    function customDie(): never {
        die();
    }

PhpStorm won't warn about not returning values when calling `customDie()`, it won't see the `switch`-`case`-example above as fall-through and it will mark code following a `never` function call as dead.

If you are using PHP 8.0 (or any older version1), you can use the custom `NoReturn` attribute since PhpStorm 2020.3:

<?php

    use JetBrains\PhpStorm\NoReturn;

    #[NoReturn]
    function customDie() {
        die();
    }

PhpStorm will then treat `customDie()` as an exit point.

1: While attributes are only supported starting with PHP 8.0, PhpStorm will still understand them even in earlier versions, though it will warn you that attributes require PHP 8.0.

Problem

Is there an attribute to mark a function that always throws an exception or dies? ``` /** @noreturn */ function customDie() { die(); } function bar() { switch( .. ) { case 1: customDie(); // <-- should not warn because there is no break case 2: xxx(); } /** @return int */ function goo() { ... customDie(); // <-- should not warn that the method is not returning an integer } ```

Original source