C++-like function-try-block proposal
| From: | enclaved at Safe-mail dot net | Date: | Mon, 27 Nov 2017 04:06:39 +0000 |
| Subject: | C++-like function-try-block proposal | ||
| Groups: | php.internals | ||
| Request: | Send a blank email to internals+get-101156@lists.php.net to get a copy of this message | ||
Greetings!
I have been referred to this mailing list by https://wiki.php.net/rfc/howto
as the first step to propose a language change. I first tried to register
on wiki.php.net as per php-src/README.SUBMITTING_PATCH in order to actually
make an RFC, only to be given an error:
Writing /srv/web-wiki/dokuwiki/conf/users.auth.php failed
I am proposing a patch (see attachment) to bring C++-like function-try-block
shorthand syntax (http://en.cppreference.com/w/cpp/language/function-try-block)
for whole-function try-catch-finally blocks:
function fuu($foo, $bar): void try
{
may_throw($foo);
may_throw($bar);
} catch (FuuException $e) {
echo $e->getMessage();
}
Since PHP is partially influenced by C++, I believe this syntax would be
a meaningful step in making PHP a little bit more intuitively compatible
with C++ practices, which may prove useful for people who come to PHP from
the C++ world (such as myself.) The expected benefit is PHP becomes yet
more familiar and comfortable for C++ programmers.
Also, this syntax saves us one set of curly braces and an indentation level,
allowing for more compact and expressive functions, and especially closures:
$s = preg_replace($re, $s, function (array $m): void try {
return find_replacement(...$m);
} catch (Throwable $e) {
return $m[0];
});
In addition to the syntactic sugar, I would like to outline another possible
merit: the very fact of such a shorthand construct existing may encourage
programmers to write functions with a consistent approach to exception handling
at whole-function level. Each such function becomes a self-contained code unit
tightly coupled with its exception handling logic, the programmer's intent
clearly outlined by the use of the proposed construct, thereby facilitating
code clarity and integrity and promoting a stricter and more rigid code style.
The proposed patch makes purely cosmetic modifications to zend_language_parser.y
grammar to augment plain functions, class methods, and closures to accept
try-catch-finally blocks as their bodies in addition to regular compound
statements. It amounts to just a handful of lines and entails no API changes.
I submitted my patch via the bugtracker: https://bugs.php.net/bug.php?id=75576
Please share your thoughts.
--Alexei Gerasimov