Bug #79867 [Nab->ReO]: Incorrect constructor promotion
| From: | nikic@php.net | Date: | Thu, 16 Jul 2020 20:57:33 +0000 |
| Subject: | Bug #79867 [Nab->ReO]: Incorrect constructor promotion | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-228087@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=79867&edit=1
ID: 79867
Updated by: nikic@php.net
Reported by: slavcopost at gmail dot com
Summary: Incorrect constructor promotion
-Status: Not a bug
+Status: Re-Opened
Type: Bug
Package: Class/Object related
Operating System: *
PHP Version: 8.0.0alpha2
Block user comment: N
Private report: N
New Comment:
I can see the argument for giving $a a null default value though, because that's what normally
happens with untyped properties. Right now constructor promotion gives you a property declaration
that (for untyped properties) you cannot achieve in any other way, which is certainly odd, and not
really intentional.
Previous Comments:
------------------------------------------------------------------------
[2020-07-16 20:53:04] nikic@php.net
> That has never been mandatory, has it?
No, and it's still not mandatory -- for example, you could also do a manual $this->a = 42
assignment if you like. The state of the parent class just needs to be initialized *somehow* and
parent::__construct() is the most typical and most robust way to do so.
------------------------------------------------------------------------
[2020-07-16 20:41:17] slavcopost at gmail dot com
> You are missing a parent::__construct() call.
That has never been mandatory, has it?
------------------------------------------------------------------------
[2020-07-16 20:39:26] slavcopost at gmail dot com
Sorry I meant the deshugaring code is like
```php
<?php
class A {
public $a;
public function __construct(
$a = 1
) {
$this->a = $a;
}
}
class B extends A {
public function __construct(
public string $b = 'hello'
) {}
}
$b = new B();
var_dump($b->a, $b->b);
```
And this code does not show warning.
------------------------------------------------------------------------
[2020-07-16 20:36:40] requinix@php.net
You still have to call the parent constructor.
------------------------------------------------------------------------
[2020-07-16 20:36:08] nikic@php.net
You are missing a parent::__construct() call. Possibly
class B extends A {
public function __construct(
public string $b = 'hello'
) {
parent::__construct(); // Use default for A::$a
}
}
or
class B extends A {
public function __construct(
$a,
public string $b = 'hello'
) {
parent::__construct($a); // Set A::$a = $a
}
}
------------------------------------------------------------------------
The remainder of the comments for this report are too long. To view
the rest of the comments, please view the bug report online at
https://bugs.php.net/bug.php?id=79867
--
Edit this bug report at https://bugs.php.net/bug.php?id=79867&edit=1