Re: Brainstorming idea: inline syntax for lexical (captured) variables
| From: | Rowan Tommins | Date: | Fri, 14 Apr 2023 06:52:22 +0000 |
| Subject: | Re: Brainstorming idea: inline syntax for lexical (captured) variables | ||
| References: | 1 2 3 4 5 6 7 8 9 10 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-120038@lists.php.net to get a copy of this message | ||
On 14 April 2023 05:35:39 BST, "Michał Marcin Brzuchalski"
<michal.brzuchalski@gmail.com> wrote:
>Have you thought about not populating property by default but instead:
>* adding "use" language construct as default to all methods?
>* adding ability to assign variable values from "use" to property if needed?
>
>Like desugar to
>$c = class ($a, $b) use ($c) {
> private $c = $c; // optional, not required, no conflicts
> public function __construct(private int $a, private int $b) use ($c) {
> $this->c = $c % 2 ? 3 : 5;
> }
> public function something() use ($c) {
> return $c;
> }
>}
This is closer to what I originally proposed, but with different syntax.
The challenge, as was pointed out to me, is that the anonymous class is compiled as a reusable class
definition on first use, and a new instance construction on each execution, so you have to think
about what happens at each stage.
In this example, you've got to first compile something where $c is an open parameter of some
sort, and make it available to all the contexts where it might be used; then, when you create the
instance, supply a value for $c, and attach it to the instance somewhere; and finally, when
something() is called, look up that attached value and make it available to the method.
In other words, the use() clause on the class ends up acting like a constructor parameter, and the
references in methods end up acting like property references. It's a lot of extra complication
to duplicate things the language already has.
Having played with it a bit while implementing, I also like the conciseness of objects with no
explicit body at all:
$who = new class use ($firstName as string, $lastName as string) {};
echo $who->firstName;
Regards,
--
Rowan Tommins
[IMSoP]