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
See the RFC for Constructor Property Promotion
This is not a bug!
The above code is a short hand syntax to
Which generates a fatal error
So you can’t initialize a typed property that is not nullable to
NULL