developer-blog:$

oop

OOP Class Immutable

Die Properties eines Object sollten niemals im nachhinein verändert werden.

Die Properties eines Object sind seine Identität. Das Object ist somit immutable.

// Falsch
class Email
{
private string $from;

    public function __construct(string $from)
    {
       $this->from = $from;
    }

    public function send(string $fromName)
    {
       $this->from = $fromName . ' <' . $this->from . '>';

       // Send email to receiver
    }
}

// Richtig
class Email
{
private string $from;

    public function __construct(string $from)
    {
       $this->from = $from;
    }

    public function send(string $fromName)
    {
       $emailFrom = $fromName . ' <' . $this->from . '>';

       // Send email to receiver
    }
}