Hey, did you get your answer?
Aug 6, 2022
7
Level 4
Constructor property promotion
Hi all. I would like a small clarification regarding constructor property promotion.
When you have a parent class and child class with constructor property promotion. What it the correct way to write the parent properties on the child class?
I think if I type protected User $user on the child class it will create the property on the Child Class overriding the parent property which is unnecessary.
// Parent
abstract class ParentClass
{
/**
* Create a new event instance.
*
* @param User $user
*/
public function __construct(protected User $user)
{
//
}
}
//Child
class ChildClass extends ParentClass
{
/**
* Create a new event instance.
*
* @param User $user
* @param AnotherClass $object
*/
public function __construct(protected User $user, public AnotherClass $object)
{
parent::__construct($user);
}
}
OR
//Child
class ChildClass extends ParentClass
{
/**
* Create a new event instance.
*
* @param User $user
* @param AnotherClass $object
*/
public function __construct(User $user, public AnotherClass $object)
{
parent::__construct($user);
}
}
Please or to participate in this conversation.