Add support for single-expression methods#58
Conversation
|
RFC has been declined |
|
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 |
| $parse->expecting('}', 'method declaration'); | ||
| } else if ('=>' === $parse->token->value) { // Single expression | ||
| $parse->forward(); | ||
| $statements= [new ReturnStatement($this->expression($parse, 0), $parse->token->line)]; |
There was a problem hiding this comment.
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])
|
This adds an inconsistency with Idea
What should workMethods: class T {
public function name() => $this->name; // 🆕
// Equivalent of
// public function name() { return $this->name; }
}Binding closures: fn($a, $b) => $a + $b;
// Equivalent of
// fn($a, $b) { return $a + $b; } // 🆕Closures: function($a, $b) => $a + $b; // 🆕
// Equivalent of
// function($a, $b) { return $a + $b; }Functions: function add($a, $b) => $a + $b; // 🆕
// Equivalent of
// function add($a, $b) { return $a + $b; }Consistency with other constructsProperty hooks: class Entry implements Value {
private $attributes= [];
public string $slug {
get => $this->attributes['slug'];
// Equivalent of
// get { return $this->attributes['slug']; }
}
}Match statement: match ($response->status()) {
204 => null,
200 => $response->value(),
404 { // 🆕 https://wiki.php.net/rfc/match_expression_v2#blocks
if ($optional) return null;
throw new NoSuchElementException('...');
},
}In all cases, a single expression should be parsed into the node representing it, while multiple statements should form a Another way to think about this is in the video https://youtu.be/bYnJA9qt_94
|
Support
|
|
Superseded by #61 |

This PR adds syntactic support for single-expression methods
See:
fn)