PHP: rfc:throw_expression
source link: https://wiki.php.net/rfc/throw_expression
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Operator precedence
If throw
becomes an expression operator precedence becomes relevant. These examples are working today.
throw $this->createNotFoundException(); // Evaluated as throw ($this->createNotFoundException()); // Instead of (throw $this)->createNotFoundException(); throw static::createNotFoundException(); // Evaluated as throw (static::createNotFoundException()); // Instead of (throw static)::createNotFoundException(); throw $userIsAuthorized ? new ForbiddenException() : new UnauthorizedException(); // Evaluated as throw ($userIsAuthorized ? new ForbiddenException() : new UnauthorizedException()); // Instead of (throw $userIsAuthorized) ? new ForbiddenException() : new UnauthorizedException(); throw $maybeNullException ?? new Exception(); // Evaluated as throw ($maybeNullException ?? new Exception()); // Instead of (throw $maybeNullException) ?? new Exception(); throw $exception = new Exception(); // Evaluated as throw ($exception = new Exception()); // Instead of (throw $exception) = new Exception(); throw $exception ??= new Exception(); // Evaluated as throw ($exception ??= new Exception()); // Instead of (throw $exception) ??= new Exception(); throw $condition1 && $condition2 ? new Exception1() : new Exception2(); // Evaluated as throw ($condition1 && $condition2 ? new Exception1() : new Exception2()); // Instead of (throw $condition1) && $condition2 ? new Exception1() : new Exception2();
The common theme here is that everything after the throw
keyword has a higher precedence. For this reason this RFC proposes to use the lowest operator precedence possible. All the current code, even if broken or strange, will continue behaving the same way. This isn't a problem because generally throw
should be the last operator you're using as every expression after it wouldn't be evaluated anyway.
The only downside of the low precedence is that a throw
between two short-circuit operators would not be possible without parentheses:
$condition || throw new Exception('$condition must be truthy') && $condition2 || throw new Exception('$condition2 must be truthy'); // Evaluated as $condition || (throw new Exception('$condition must be truthy') && $condition2 || (throw new Exception('$condition2 must be truthy'))); // Instead of $condition || (throw new Exception('$condition must be truthy')) && $condition2 || (throw new Exception('$condition2 must be truthy'));
But I see little use for code like this.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK