-
Notifications
You must be signed in to change notification settings - Fork 7.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Uninitialized promoted constructor property even with default value #18106
Comments
Hi @Pierstoval. This is essentially a duplicate of #16546. It does not qualify as a bug, given that it was explicitly proposed this way: https://wiki.php.net/rfc/constructor_promotion#desugaring
|
Should I instead suggest a new RFC "fixing" this behavior for DX? I mean, the only solutions to apply default values would be hacks (like using the Reflection API to enforce using the default value promoted in the constructor, or, as I did on a project, using a bounded closure after construction time to enforce an initialized state on props), or completely removing the properties having a default value. At first it sounds counter-intuitive since we're talking about default class properties values, so we should expect default values to be applied both in the constructor and in the property itself. |
@Pierstoval Please check the RFC and the rationale for why it wasn't done this way in the first place.
class C {
public function __construct(
public $prop = new \stdClass();
) {}
}
// desugars to
class C {
public $prop = new \stdClass(); // This is not valid code
...
}
|
After your comment, and more discussion on the public Slack, turns out PHP isn't compatible with fixing this issue (at least "yet"), because constructor has lots of side-effects, is public (therefore can be called more than once), and the current implementation for Closing, thanks for your comment @iluuu1994 |
Description
TL;DR: 3v4l link here to reproduce: https://3v4l.org/8XAEr
When having a class with promoted properties (readonly or not) having default values, the construction with
ReflectionClass::newInstanceWithoutConstructor()
doesn't initialize the properties.Example with this class:
Normal construction does properly defines the property with the default value.
However, when using the Reflection API, the default value isn't provided:
This will result in this inconsistent object state:
Here, since the promoted property has a default value, we should expect the same output as the previous example.
This does not happen if the property isn't promoted:
Note: the exact same happens with
readonly
properties, the code compiles even thoughreadonly
properties should not have a default value, but creating the object with the Reflection API without its constructor will still result in thisuninitialized
state.PHP Version
Starts at 8.2.0 upwards
Operating System
No response
The text was updated successfully, but these errors were encountered: