DEV Community

Discussion on: Breaking Encapsulation with traits in PHP

Collapse
 
sebastianr1982 profile image
Sebastian Rapetti

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.

Collapse
 
purplebooth profile image
Billie

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.

Collapse
 
sebastianr1982 profile image
Sebastian Rapetti

This is ok as your example with abstract:
github.com/linna/framework/blob/ma...

This need refactor:
github.com/linna/framework/blob/ma...