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

-- 
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php

Reply via email to