rfc:lexical-anon

This is an old revision of the document!


PHP RFC: Lexical Scope Support for Anonymous Classes

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;
}; 

Syntax Choices

Placing the [use(...)] anywhere else in the class declaration seems to be confusing, the current position seems the obvious choice.

It has been suggested that it would be better to have [use(...)] on each function declaration. This would lead to a lot of repetition, and fragmented code that is more difficult to reason about.

The cognitive overhead of “anything use'd by the declaration is a member property” is almost nil.

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

  1. the version(s) it was merged to
  2. a link to the git commit(s)
  3. 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.

rfc/lexical-anon.1461071796.txt.gz · Last modified: 2017/09/22 13:28 (external edit)