Hi
Good example, in your code the trait access a private property of the class.
When I use 'traits' I pay attention to not use class properties. It takes longer to write code that does not mix class and trait.
I think that a trait should provide only methods to a class, for extends funcionalities. Trait have own encapsulation.
Yeah, and you can even use abstracts to make the compiler check to see if the method is there too.
<?php declare(strict_types=1); namespace PurpleBooth\EncapsulationTraits; trait ExampleTrait { public function changeNameTrait(): void { $this->setName("I don't break encapsulation"); } abstract public function setName(string $name): void; }
However, I think it's still too easy for someone who doesn't know this to make this mistake. When you use other methods the encapsulation is enforced by scoping in the compiler which is much stronger, than relying on humans to not make a mistake.
This is ok as your example with abstract: github.com/linna/framework/blob/ma...
This need refactor: github.com/linna/framework/blob/ma...
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Hi
Good example, in your code the trait access a private property of the class.
When I use 'traits' I pay attention to not use class properties. It takes longer to write code that does not mix class and trait.
I think that a trait should provide only methods to a class, for extends funcionalities. Trait have own encapsulation.
Yeah, and you can even use abstracts to make the compiler check to see if the method is there too.
However, I think it's still too easy for someone who doesn't know this to make this mistake. When you use other methods the encapsulation is enforced by scoping in the compiler which is much stronger, than relying on humans to not make a mistake.
This is ok as your example with abstract:
github.com/linna/framework/blob/ma...
This need refactor:
github.com/linna/framework/blob/ma...