throw_unless - Throws an exception unless provided expression evaluates to true.


throw_unless(mixed $expression, ?Throwable $throwable = null): mixed

This function can replace assert() function. Unlike assert(), throw_unless() cannot be disabled.


Any valid PHP expression.
An optional throwable object. If not provided \Exception will be used.

Return value

If you passed a value as parameter, then the same value will be returned. If you used an expression $expression, the result of the expression will be returned.


I wanted to use assert() this way:

assert($user instanceof \App\Entity\User, new Exception('Invalid user'));

Because assert can be disabled, I had to rewrite the code:

if(!($user instanceof \App\Entity\User)) {
    throw new Exception('Invalid user');

Using throw_unless() I can write this in a single line again:

use function Jawira\TheLostFunctions\throw_unless;

throw_unless($user instanceof \App\Entity\User, new Exception('Invalid user'));