Re: RFC: Anonymous Class Lexical Scope
| From: | Rowan Collins | Date: | Tue, 19 Apr 2016 14:37:11 +0000 |
| Subject: | Re: RFC: Anonymous Class Lexical Scope | ||
| References: | 1 2 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-92466@lists.php.net to get a copy of this message | ||
Nikita Popov wrote on 19/04/2016 15:18:
I'd like to suggest an alternative syntax:
$foo = 42;
return new class {
private $bar = $foo;
public function getBar() { return $this->bar; }
}
That is, allow properties inside the anonymous class to be initialized
based on values from the surrounding scope.
The problem with this is that it violates PHP's normal scoping rules, because the variable is crossing scopes "uninvited". It makes it more explicit where the variable is going *to*, but hides where it is coming *from*.
Perhaps a Trait-like syntax might work?
$foo = 42;
return new class {
use $foo as private $bar;
public function getBar() { return $this->bar; }
}
This makes it clear both that $foo is being imported from somewhere, and that it is being saved to a particular private member.
Regards,
--
Rowan Collins
[IMSoP]