[php-src] Issue #14062: Reflection: promoted constructor parameter has no default value
| From: | Zekfad | Date: | Sat, 27 Apr 2024 18:22:20 +0000 |
| Subject: | [php-src] Issue #14062: Reflection: promoted constructor parameter has no default value | ||
| Groups: | php.bugs | ||
| Request: | Send a blank email to php-bugs+get-246827@lists.php.net to get a copy of this message | ||
Issue: https://github.com/php/php-src/issues/14062
Author: Zekfad
### Description
The following code:
```php
<?php
class A
{
public function __construct(
public string $bar = 'test',
string $foo,
) {
}
}
$r = new ReflectionClass(A::class);
foreach ($r->getConstructor()->getParameters() as $param) {
$a = [
'name' => $param->name,
'promoted' => $param->isPromoted(),
'type name' => $param->getType()->getName(),
'has default value' => $param->isDefaultValueAvailable(),
];
if ($param->isDefaultValueAvailable()) {
$a += [
'default value' => $param->getDefaultValue(),
];
}
var_dump($a);
}
```
Resulted in this output:
```
array(4) {
["name"]=>
string(3) "bar"
["promoted"]=>
bool(true)
["type name"]=>
string(6) "string"
["has default value"]=>
bool(false)
}
array(4) {
["name"]=>
string(3) "foo"
["promoted"]=>
bool(false)
["type name"]=>
string(6) "string"
["has default value"]=>
bool(false)
}
```
But I expected this output instead:
```
array(5) {
["name"]=>
string(3) "bar"
["promoted"]=>
bool(true)
["type name"]=>
string(6) "string"
["has default value"]=>
bool(true)
["default value"]=>
string(4) "test"
}
array(4) {
["name"]=>
string(3) "foo"
["promoted"]=>
bool(false)
["type name"]=>
string(6) "string"
["has default value"]=>
bool(false)
}
```
Changing order of parameters makes the difference, e.g. following works as expected:
```php
<?php
class A
{
public function __construct(
string $foo,
public string $bar = 'test',
) {
}
}
class A
{
public function __construct(
public string $foo = 'test2',
public string $bar = 'test',
) {
}
}
```
But this doesn't work as well:
```php
<?php
class A
{
public function __construct(
public string $qux = 'test1',
public string $foo = 'test2',
public string $bar,
public string $baz = 'test3',
) {
}
}
```
Looks like finding new required parameter makes all previous parameters to required (which is ok for
PHP <8, but in PHP 8 we have named parameters).
### PHP Version
PHP 8.3.6 (cli) (built: Apr 10 2024 14:54:14) (ZTS Visual C++ 2019 x64)
### Operating System
Microsoft Windows [Version 10.0.19045.4291]