Function list declaration syntax?
| From: | Mike Schinkel | Date: | Tue, 05 Oct 2021 17:47:27 +0000 |
| Subject: | Function list declaration syntax? | ||
| Groups: | php.internals | ||
| Request: | Send a blank email to internals+get-116231@lists.php.net to get a copy of this message | ||
Hi all,
This email proposes a shorthand syntax for declaring a list of single-expression functions.
A similar albeit more verbose attempt to provide short functions[1] failed late last year, but I was
recently inspired by Sebastian Bergmann's Type library[2] that he referenced in a comment on
another thread.
Consider the
Type class[3] in the SebastianBergmann\Type namespace. It
contains 60 lines of function declaration to define 14 functions that all return false.
Even though it really is a simple class it is rather hard to wrap one's head around quickly
because of all the bloating boilerplate required. At least IMO.
Consider instead if we had the following syntax?
public function list: bool
{
isCallable() => false,
isFalse() => false,
isGenericObject() => false,
isIntersection() => false,
isIterable() => false,
isMixed() => false,
isNever() => false,
isNull() => false,
isObject() => false,
isSimple() => false,
isStatic() => false,
isUnion() => false,
isUnknown() => false,
isVoid() => false,
}
The idea here is to group a 'list' of functions — in this case of the same type — and
then use shortened single expression fn() syntax for each function. And with a monospace font in
your editor of choice this code could be made even easier to grok by left-aligning the return
values.
I chose the keyword list because it is already a reserved word, but the word
case could also be used for the same reason, if people prefer that.
Further, instead of function list or function case we could have fn
list, fn case, fn() list or fn() case, whichever feels
best to the most people.
This could also work for abstract functions noting that the typehint is applied to each function
instead of the list declaration, e.g.:
abstract public function list
{
isAssignable(self $other): bool;
name(): string;
allowsNull(): bool;
}
Those two changes shorten Type.php from 140 lines down to 90 lines, and IMO, make the class much
easier to read. You can see it here[4].
One more example, this time his NullType class[5] using mixed type hints and going from
a total of 38 lines down to 26 lines[6]:
public function list
{
name(): string => 'null',
asString(): string => 'null',
allowsNull(): bool => true,
isNull(): bool => true,
}
What do you think? Is this approach any more appealing than the last one proposed?
-Mike
[1] https://wiki.php.net/rfc/short-functions
[2] https://github.com/sebastianbergmann/type
[3] https://github.com/sebastianbergmann/type/blob/master/src/type/Type.php
[4] https://gist.github.com/mikeschinkel/6f8c9cf6700a75e75e2725db1ed4da61
[5] https://github.com/sebastianbergmann/type/blob/master/src/type/NullType.php
[6] https://gist.github.com/mikeschinkel/a93aabd61127b0c3ba28c5caf4ebe005