Skip to content

[RFC] Guard statement #5578

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed

[RFC] Guard statement #5578

wants to merge 1 commit into from

Conversation

alherd-by
Copy link

I want to propose new decision-making statement - guard. It is similar to if, but executes body only if expression equals false and must contains code that changes flow of execution: throw, return etc.

guard ($condition = false) else {
     //code
     thrown new \LogicException();
}

Inspired by Swift lang https://docs.swift.org/swift-book/ReferenceManual/Statements.html#grammar_if-statement

Work in progress.

@zmitic
Copy link

zmitic commented May 16, 2020

Is it possible to have something similar to arrow functions syntax? For comparison:

// some controller:

public function edit(Product $product): Response
{
    guard($user = $this->getUser()) => new RedirectResponse();
    guard($product->getOwner() === $user) => throw new SecurityException();
}

vs

// some controller:

public function edit(Product $product): Response
{
    if (!$user = $this->getUser()) {
        return  new RedirectResponse();
    }
    if ($product->getOwner() !== $user) {
        throw new SecurityException();
    }
}

First example with short guard is much cleaner and shorter when compared to assignments in if and negative comparison.

In reality, most usages for this is early-exit and unlikely to have more than 1 line of code (even RFC has such examples).

@alherd-by alherd-by closed this May 17, 2020
@alherd-by
Copy link
Author

Withdrawn

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants