Why can't an expression be assigned to a PHP member variable by default?

Viewed 29

The following code produces a fatal error in PHP:

class A {}
class B {
    private A $a = new A();
}

PHP Fatal error: Constant expression contains invalid operations

Of course, you can move this assignment into B's constructor, and then it will run. But why does PHP limit you to constant values in this context, when the analogous operation is allowed in e.g. Java?

1 Answers

Java and PHP are different. They do things differently, particularly when it comes to the compilation step.

With PHP8.1, you can now use new in an initializer which is functionally the same for an object that is instantiated.

Objects can now be used as default parameter values, static variables, and global constants, as well as in attribute arguments.

This allows for the following:

<?php
class A {}
class B {
    public function __construct(public A $a = new A())
    {
    }
}

var_dump(new B);

You can see it running in PHP8.1 and above at https://3v4l.org/W4DSG

Related