Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot use null as default value for parameter in PHP-8

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?


1 Answers

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) {}
}
like image 59
Phil Avatar answered Jul 22 '26 06:07

Phil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!