skip to Main Content

In php-8 and older versions the following code works

class Foo {
    public function __construct(string $string = null) {}
}

But in php-8, along with property promotion, it throws an error

class Foo {
    public function __construct(private string $string = null) {}
}

Fatal error: Cannot use null as default value for parameter $string of type string

Making the string nullable works though

class Foo {
    public function __construct(private ?string $string = null) {}
}

So is this a bug too or intended behaviour?

2

Answers


  1. See the RFC for Constructor Property Promotion

    …because promoted parameters imply a property declaration, nullability must be explicitly declared, and is not inferred from a null default value:

    class Test {
        // Error: Using null default on non-nullable property
        public function __construct(public Type $prop = null) {}
     
        // Correct: Make the type explicitly nullable instead
        public function __construct(public ?Type $prop = null) {}
    }
    
    Login or Signup to reply.
  2. This is not a bug!

    class Foo {
        public function __construct(private string $string = null) {}
    }
    

    The above code is a short hand syntax to

    class Foo {
        private string $string = null;
        public function __construct(string $string) {
            $this->string  = $string;
        }
    }
    

    Which generates a fatal error

    Fatal error: Default value for property of type string may not be
    null.

    So you can’t initialize a typed property that is not nullable to NULL

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search