PHP 8.1 – Default parameters with “new” keyword

PHP 8.1 – Default parameters with “new” keyword

abstract gradients

Currently we could only assign a default parameter value of nullarray or primitive types in functions and methods. In PHP 8.1 we will be able to provide any custom class as default value for our expected function parameter. This includes defining a class variables inside the parameters as well.

new expressions are allowed as part of certain 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 or an anonymous class 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(
    $a = new (CLASS_NAME_CONSTANT)(), // dynamic class name
    $b = new class {}, // anonymous class
    $c = new A(...[]), // argument unpacking
    $d = new B($abc), // unsupported constant expression
) {}

More about PHP 8.1

Read about all PHP 8.1 features and changes in here.