DEV Community

Discussion on: Breaking Encapsulation with traits in PHP

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...