Skip to content

Conversation

thekid
Copy link
Member

@thekid thekid commented Jul 19, 2025

This PR adds syntactic support for single-expression methods

class Person {
  public function __construct(private string $name) { }

  // Equivalent of public function name() { return $this->name; }
  public function name() => $this->name;
}

See:

@thekid
Copy link
Member Author

thekid commented Aug 2, 2025

RFC has been declined

@thekid
Copy link
Member Author

thekid commented Oct 3, 2025

This would be consistent with the abbreviated property hooks syntax:

class User {
  public function __construct(private string $first, private string $last) {}
 
  // Long form
  public string $fullName {
    get { 
      return $this->first.' '.$this->last;
    }
  }

  // Short form
  public string $fullName {
    get => $this->first.' '.$this->last;
  }

  // Long form
  public string $username {
    set(string $value) {
      $this->username= strtolower($value);
    }
  }
 
  // Short form
  public string $username {
    set => strtolower($value);
  }
}

...which sets => [exor] as an equivalent of { return [expr]; }.

$parse->expecting('}', 'method declaration');
} else if ('=>' === $parse->token->value) { // Single expression
$parse->forward();
$statements= [new ReturnStatement($this->expression($parse, 0), $parse->token->line)];
Copy link
Member Author

@thekid thekid Oct 3, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is inconsistent with how short and long forms of property accessors are parsed - they make use of the Block class:

  • body for => [expr]: Expr
  • body for { [statement]; }: Block([Statement])

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.

1 participant