Trait constructors / property initialization
| From: | Andreas Hennings | Date: | Thu, 13 Jan 2022 14:36:14 +0000 |
| Subject: | Trait constructors / property initialization | ||
| Groups: | php.internals | ||
| Request: | Send a blank email to internals+get-116879@lists.php.net to get a copy of this message | ||
Hello list,
I want to bring up a topic that has bothered me whenever I use traits.
I don't have a solution proposal for it, yet, unfortunately.
I was going to comment in the other thread about traits, but it seems
better suited for a new discussion.
----------
Traits allow to share code between classes of different inheritance chains.
They can be used instead of composition, or they can be used to help
with composition - e.g. a trait can expose functionality from a
specific injected dependency.
----------
When using base classes, we can follow a convention to always call the
parent constructor.
We can even make the properties in the base class private, to fully
encapsulate them.
But:
When using properties in traits, how can I make sure that they are
properly initialized in the class constructor?
Also, what if I want to provide an init method with specific logic to
set that property? How can I make sure that method will be called in
the constructor?
I found that Psalm can detect "PropertyNotSetInConstructor", which is
also applied to properties from traits.
But this is not as straightforward as calling a parent constructor.
Can and should we provide a language-level solution for this?
Or should this be left to static analysis tools and IDEs?
Cheers,
Andreas