Re: Constructor promoted property and default value
| From: | Robert Landers | Date: | Wed, 25 Oct 2023 19:17:47 +0000 |
| Subject: | Re: Constructor promoted property and default value | ||
| References: | 1 2 3 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-121465@lists.php.net to get a copy of this message | ||
On Mon, Oct 23, 2023 at 6:22 PM Pierre <pierre-php@processus.org> wrote:
>
> Le 23/10/2023 à 18:11, Saki Takamachi a écrit :
> >> If I understand your use case properly, you should be confused by properties with
> >> default values that are not constructor-promoted as well ? Am I wrong ? In this case, your problem
> >> is not with promoted properties ?
> > If we specify it the way you say, the initial values of the constructor arguments will be
> > available even when the constructor is not called.
> >
> > Such behavior felt a little counterintuitive.
>
> Which then would simply be the same behavior as properties when not
> promoted but declared in the class body instead:
>
> ```php
>
> class Foo
> {
> public $val = 'abc';
> }
>
> $redis_foo = serialize(new Foo());
>
> $foo = unserialize($redis_foo);
> var_dump($foo->val);
> // string(3) "abc"
>
> ```
>
> Right ?
>
> What's the most disturbing in my opinion is that: `class Foo { public
> string $val = 'abc' }
and class Foo { public function
> __construct(public string $val = 'abc' ) {}}` don't yield the same
> behavior at the time.
>
> Regards,
>
> --
>
> Pierre
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.php
>
Here's a nice and simple example:
https://3v4l.org/DU0tG
class A {
public string $default = 'default';
}
class B {
public function __construct(public string $default = 'default') {}
}
$a = new A();
echo "Original A: {$a->default}\n";
$b = new B();
echo "Original B: {$b->default}\n";
$a = (new ReflectionClass($a))->newInstanceWithoutConstructor();
echo "New A: {$a->default}\n";
$b = (new ReflectionClass($b))->newInstanceWithoutConstructor();
echo "New B: {$b->default}\n"; // crashes here
Robert Landers
Software Engineer
Utrecht NL