loading...

re: Breaking Encapsulation with traits in PHP VIEW POST

TOP OF THREAD FULL DISCUSSION
re: 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....
 

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.

 
Code of Conduct Report abuse