This is an old revision of the document!
PHP RFC: Lexical Scope Support for Anonymous Classes
- Version: 0.1
- Date: 2016-04-19
- Author: krakjoe
- Status: Draft
- First Published at: http://wiki.php.net/rfc/lexical-anon
Introduction
Anonymous classes are cumbersome to use because they lack support for lexical scope variables.
If the anonymous class has dependencies, they must be injected via the constructor, which is verbose, repetitive, and widens the margin for error considerably.
Proposal
We allow anonymous classes to import variables into their property table using the familiar syntax.
The following syntax is used:
new class [extends Parent] [implements Interface] [use(...)] {}
Where use is one or more variables, property references, or a references to either.
The following code:
$glow = 5; $foo = new class use($glow) { };
Is functionally equivalent to:
$glow = 5; $foo = new class($glow) { public function __construct($glow) { $this->glow = $glow; } private $glow; };
By default, imported variables shall be declared private members of the anonymous class unless the class declaration overrides this behaviour, as the following example shows:
$glow = 5; $foo = new class() use($glow) { public $glow; };
References are also accepted, so that the following code:
$glow = 5; $foo = new class() use(&$glow) { };
Is functionally equivalent to:
$glow = 5; $foo = new class($glow) { public function __construct(&$glow) { $this->glow =& $glow; } private $glow; };
Backward Incompatible Changes
What breaks, and what is the justification for it?
Proposed PHP Version(s)
7.1
RFC Impact
To Existing Extensions
Trivial changes for new opcodes and new sequences.
To Opcache
Will need adjustment, rather trivial (if you are Dmitry)
Open Issues
Make sure there are no open issues when the vote starts!
Proposed Voting Choices
2/3 majority required, simple yes/no vote.
Patches and Tests
Implementation
After the project is implemented, this section should contain
- the version(s) it was merged to
- a link to the git commit(s)
- a link to the PHP manual entry for the feature
References
Links to external references, discussions or RFCs
Rejected Features
Keep this updated with features that were discussed on the mail lists.