The necessity of multi-line short closures in PHP

PHP 8.1 is already touching the sky but there is this one feature which really gets a toll on PHP developers. This is multi-line short closures. The RFC calls them “Auto-capturing multi-statement closures” but I hope you don’t mind me using the somewhat shorter name.

PHP 8.1. Version

If you’re using an active version of PHP 8.1, you are already familiar about short closures— a.k.a. “arrow functions”. Most importantly, one of the major drawbacks are that these versions only support one-line expressions. These are also used as the return value.

RFC and short closures

The multi-line short closures RFC by Nuno and Larry aims to solve that problem, in — what I think is — an elegant way.

Some people are skeptical about this RFC though, and I want to address their arguments and share why I think it’s still a worthwhile addition. Though first, I’ll show you what the RFC is about. Keep in mind this is a proposal, and not added to PHP yet!

There are two important things to note about multi-line short closures:

  • they have access to the variables in the upper scope without needing use; and
  • they don’t automatically return the last expression, which makes sense since there can be several expressions in a multi-line closure.

You might have already noticed it, but the RFC introduces an elegant kind of symmetry in how you can create closures:

  • on the one hand there’s function and fn, the first one doesn’t auto-capture variables from the outside, the second one does; and
  • on the other hand there’s { … } or =>, using curly brackets allow you to write multiple lines, while => only accepts one expression, but also returns it.

Because of this symmetry, all of the following code samples are possible and all of them behaving a little differently.

Hence, you might be now used to closures not auto-importing variables. After all, this has been going on for the past whole decade. However, bear this in mind this update was only made as a necessity back then. All arguments for only using explicit capture have been nullified by time, a great sign that PHP is maturing even more.

Leave a Reply

Your email address will not be published. Required fields are marked *