Menu

PHP throw Expression: ?? throw and ?: throw Explained
📰

PHP throw Expression: ?? throw and ?: throw Explained

DEV Community: laravel·devTalk·1 day ago
#1mEhm1Nn
#devtolaravel#devto#dev#throw#throws
Reading 0:00
15s threshold

You fetch a value, check whether it is missing, and throw if it is. Every PHP codebase has this four-line block hundreds of times. Since PHP 8.0, throw is an expression instead of a statement, which means it can sit on the right side of ?? or ?: and collapse the whole block into one line. In Laravel, abort() gives you the same trick. I tested the edge cases on PHP 8.3, including the one where ?? and ?: give opposite answers, because that is where the bugs hide.

Before and after

// Before $path = $config [ 'path' ] ?? null ; if ( $path === null ) { throw new RuntimeException ( 'Missing config: path' ); }

// After (PHP 8.0+) $path = $config [ 'path' ] ?? throw new RuntimeException ( 'Missing config: path' );

Enter fullscreen mode

Exit fullscreen mode

If the key exists, $path gets its value. If it is missing or null , the exception is thrown. The change came from the "throw expression" RFC by Ilija Tovilo, accepted with 46 votes for and 3 against.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.