33: Move Returns Out of finally Blocks
Overview
Section titled “Overview”Keep resource cleanup in finally and return the result on the success path. Returning from finally is deprecated in PHP 8.6 because it can replace an earlier return or suppress an exception.
Prerequisites
Section titled “Prerequisites”- PHP 8.6 CLI. Confirm the version with
php --version. - Review the previous chapter if you’re following the series in order.
Allow about 10 minutes for the walkthrough and exercise.
What You’ll Build
Section titled “What You’ll Build”A runnable return-in-finally.php example.
Step 1: Run the example (~5 min)
Section titled “Step 1: Run the example (~5 min)”Run the following from the root of the Code with PHP repository.
php code/php-8-6/33-return-in-finally/return-in-finally.php<?php
declare(strict_types=1);
function writeNote(string $note, bool $simulateFailure = false): int{ $stream = fopen('php://temp', 'w+'); if ($stream === false) { throw new RuntimeException('Cannot open temp stream'); }
try { if ($simulateFailure) { throw new RuntimeException('Write rejected'); } $written = fwrite($stream, $note); if ($written === false || $written !== strlen($note)) { throw new RuntimeException('Incomplete write'); } return $written; } finally { fclose($stream); }}
echo writeNote('hello'), " bytes\n";try { writeNote('hello', true);} catch (RuntimeException $error) { echo $error->getMessage(), PHP_EOL;}Expected Result
Section titled “Expected Result”5 bytesWrite rejectedWhy It Works
Section titled “Why It Works”PHP executes finally as control leaves try, including when an exception is propagating. With cleanup alone in that block, callers still receive the successful result or the original exception.
Exercise
Section titled “Exercise”Pass an empty string as valid input. Confirm that it prints a zero byte count on that path and still propagates exceptions when explicitly asked to fail.
Wrap-up
Section titled “Wrap-up”Continue with Move Results and Generators Out of Object Lifecycles.