Every error reported by PHPStan has an error identifier. Here’s a list of all error identifiers. In PHPStan Pro you can see the error identifier next to each error and filter errors by their identifiers.
Code example #
<?php declare(strict_types = 1);
function doFoo(): int
{
try {
return computeValue();
} finally {
return 1;
}
}
Why is it reported? #
A return statement inside a finally block is deprecated in PHP 8.6. A return in finally silently overrides the value returned from the try or catch block, and also discards any exception thrown from them. The exception is never seen by the caller, which makes bugs hard to find.
The error is reported for every return statement found directly in the finally block, including ones nested in if, loops, or a try/catch inside it. Returns inside closures, arrow functions, functions, and classes declared in the finally block are not reported.
The error is reported when the analysed PHP version is 8.6 or newer. See phpVersion to configure which PHP versions are analysed.
How to fix it #
Move the return out of the finally block, and use finally only for cleanup:
<?php declare(strict_types = 1);
function doFoo(): int
{
try {
- return computeValue();
+ $result = computeValue();
+ } catch (\Throwable $e) {
+ $result = 1;
} finally {
- return 1;
+ cleanUp();
}
+
+ return $result;
}
If exceptions from the try block should reach the caller, drop the catch block and keep only the cleanup in finally:
<?php declare(strict_types = 1);
function doFoo(): int
{
try {
- return computeValue();
+ $result = computeValue();
} finally {
- return 1;
+ cleanUp();
}
+
+ return $result;
}
How to ignore this error #
You can use the identifier finally.deprecatedReturn to ignore this error using a comment:
// @phpstan-ignore finally.deprecatedReturn
codeThatProducesTheError();
You can also use only the identifier key to ignore all errors of the same type in your configuration file in the ignoreErrors parameter:
parameters:
ignoreErrors:
-
identifier: finally.deprecatedReturn
Rules that report this error #
- PHPStan\Rules\Exceptions\ReturnInFinallyRule [1]