In PHP, throw is a statement. It can be used in only those places where a statement is allowed. But arrow functions, coalesce operator and the ternary operators allow only expressions. So we can't throw a exceptions in below situations:
<?php
$name = $_GET['name'] ?? throw new \Exception('Name not found');
$point = isset($student) ? $student->point : throw new \Exception('Student not found');
$closure = fn() => throw new \Exception('Closure not allowed');
Throw is an expression now
So, throw now can be used anywhere in the language where both expression is allowed.
Note: Current implementation has a controversial side too. Throw now can be used in IF statement.
<?php
$allow = false;
if($allow === true || throw new \Exception('$allow must be true')) {
echo '$allow is true';
}
// this will throw a exception if allow is false
Write comment about this article: