Promoted properties can be in constructor only
10 }
11
12 // invalid: cannot declare promoted property outside a constructor
13 public function setName(public string $firstName, public string $lastName): void14 {
15 }
16}
Promoted property parameter $properties can not be variadic
5class Member
6{
7 // invalid: Cannot declare variadic promoted property
8 public function __construct(public ...$properties) 9 {
10 }
11}
Promoted properties are not allowed in abstract constructors
5abstract class AbstractUser
6{
7 // invalid: Cannot declare promoted property in an abstract constructor
8 abstract public function __construct(public string $firstName, public string $lastName); 9
10 abstract public function getUser(): array
11 {
Description
Invalid usage of constructor property promotion was found, which will result in a fatal runtime error.
This issue can be raised for any of the following cases:
- Trying to use constructor property promotion before PHP 8.0. This feature is only available in PHP 8.0 and later.
- Trying to use constructor property promotion outside of any constructor. This syntax is only allowed in the
__construct()
method. - Trying to use constructor property promotion in abstract constructors.
- Trying to pass variadic parameters while using constructor property promotion.
Bad practice
class User
{
// invalid: promoted properties cannot be declared outside a constructor
public function setName(public string $firstName, public string $lastName): void
{
}
}
abstract class User
{
// invalid: promoted properties cannot be declared in an abstract constructor
abstract public function __construct(public string $firstName, public string $lastName);
}
class User
{
// invalid: promoted properties cannot be variadic
public function __construct(public ...$properties)
{
}
}
Recommended
Only use promoted properties in non-abstract constructors:
class User
{
public function __construct(public string $firstName, public string $lastName)
{
}
}