rfc:new_in_initializers

This is an old revision of the document!


PHP RFC: New in initializers

Introduction

This RFC proposes to allow use of new expressions inside initializer expressions, including for property and parameter default values.

Currently, code such as the following is not permitted:

class Test {
    public function __construct(
        private Logger $logger = new NullLogger,
    ) {}
}

Instead, it is necessary to write code along the following lines:

class Test {
    private Logger $logger;
 
    public function __construct(
        ?Logger $logger = null,
    ) {
        $this->logger = $logger ?? new NullLogger;
    }
}

This makes the actual default value less obvious (from an API contract perspective), and requires the use of a nullable argument.

This RFC proposes to relax this restriction and allow the use of new inside all initializer expressions.

Proposal

new expressions are allowed as part of initializer expressions. It is possible to pass arguments to the constructor, including the use of named arguments:

// All allowed:
function test(
    $foo = new A,
    $bar = new B(1),
    $baz = new C(x: 2),
) {
}

The use of a dynamic or non-string class name is not allowed. The use of argument unpacking is not allowed. The use of unsupported expressions as arguments is not allowed.

// All not allowed (compile-time error):
function test(
    $foo = new (CLASS_NAME_CONSTANT)(), // dynamic class name
    $bar = new A(...[]), // argument unpacking
    $baz = new B($abc), // unsupported constant expression
) {}

Affected positions are static variable intializers, constant and class constant initializers, static and non-static property intializers, parameter default values, as well as attribute arguments:

static $x = new Foo;
 
const C = new Foo;
 
#[AnAttribute(new Foo)]
class Test {
    const C = new Foo;
    public static $prop = new Foo;
    public $prop = new Foo;
}
 
function test($param = new Foo) {}

Order of evaluation

Initializer expressions could always contain side-effects through autoloaders or error handlers. However, support for new and the accompanying construct calls make side-effect a more first-class citizen in initializer expressions, so it is worthwhile to specify when and in what order they are evaluated. This depends on the type of initializer:

  • Static variable initializers are evaluated when control flow reaches the static variable declaration.
  • Global constant initializers are evaluated when control flow reaches the constant declaration.
  • Attribute arguments are evaluated from left to right on every call of ReflectionAttribute::getArguments() or ReflectionAttribute::newInstance().
  • Parameter default values are evaluated from left to right on every call to the function where the parameter is not explicitly passed.
  • Property default values are evaluated in order of declaration (with parent properties before properties declared in the class) when the object is instantiated. This happens before the constructor is invoked. If an exception is thrown during evaluation, the object destructor will not be invoked.
  • The time of evaluation for static properties and class constants is unspecified. Currently, all static property and class constant initializers are evaluated on certain first uses of the class. (TODO?)

Interaction with reflection

Initializers, or values based on initializers, can be accessed through Reflection in various ways. This section specifies how the different methods behave:

  • ReflectionFunctionAbstract::getStaticVariables(): Returns the current value of the static variables and also forces evaluation of any initializers that haven't been reached yet.
  • ReflectionParameter::getDefaultValue(): Evaluates the default value (on each call).
  • ReflectionParameter::isDefaultValueConstant() and ReflectionParameter::getDefaultValueConstantName(): Do not evaluate the default value.
  • ReflectionClassConstant::getValue(), ReflectionClass::getConstants() and ReflectionClass::getConstant(): Returns value of the class constant(s), evaluating the initializer if this has not happened yet. (The returned value is the same as the actual value of the class constant, not a separate evaluation.)
  • ReflectionClass::getDefaultProperties() and ReflectionProperty::getDefaultValue(): Evaluates initializers for both static and non-static properties on each call. (NOTE: Due to a pre-existing implementation bug, if opcache is not used, the current value is used instead of the default value for static properties. This is incorrect, and should be fixed.)
  • ReflectionAttribute::getArguments() and ReflectionAttribute::newInstance(): Evaluate attribute arguments on each call.
  • ReflectionObject::newInstanceWithoutConstructor(): Evaluates and assigns default values, even though the constructor is not invoked. (TODO?)

Recursion protection

If the evaluation of an object property default value results in recursion, an Error exception is thrown:

class Test {
    public $test = new Test;
}
 
new Test;
// Error: Trying to recursively instantiate Test while evaluating default value for Test::$test

Backward Incompatible Changes

None.

Future Scope

This RFC is narrow in that it only adds support for new expressions. However, it also lays the technical groundwork for supporting other expressions like calls.

Vote

Yes/No.

rfc/new_in_initializers.1614865685.txt.gz · Last modified: 2021/03/04 13:48 by nikic