PHP

イミュータブルPHP クソコード動画「カプセル化」から学ぶ

 

 

問題

  • データが書き換わってしまってしまう。

 

対応

  • イミュータブルにする
  • getter/setterをつくらない

 

 

ミュータブル(可変)

 

client.php

<?php

require_once('mmutable.php');

$pokemon = new Pokemon('ミュウ');

$pokemon->setName('ピカチュー');
echo $pokemon->getName(); // ピカチュー

 

mmutable.php

<?php

final class Pokemon
{
    private $name;

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

    public function getName(): string
    {
        return $this->name;
    }

    public function setName(string $name): void
    {
        $this->name = $name;
    }
}

 

 

実行結果

ピカチュー

上書きされてしまっている。

 

 

 

 

イミュータブル(不変)

 

client.php

<?php

require_once('immutable.php');

$pokemon = new Pokemon('ミュウ');

$pokemon->setName('ピカチュー');
echo $pokemon->getName(); // ミュウ

 

 

immutable.php

<?php

final class Pokemon
{
    private $name;

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

    public function getName(): string
    {
        return $this->name;
    }

    //public function setName(string $name): self
    //{
    //    return new self($name);
    //}

    public function setName(string $name): self
    {
        $new = clone $this;
        $new->name = $name;
        return $new;
    }
}

 

実行結果

 

ミュウ

書き変わらない。

 

 

Amazonおすすめ

iPad 9世代 2021年最新作

iPad 9世代出たから買い替え。安いぞ!🐱 初めてならiPad。Kindleを外で見るならiPad mini。ほとんどの人には通常のiPadをおすすめします><

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)