31
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHP7.1からprivate constが書ける

Posted at

タイトル落ちですが、以下のような実装でお悩みの方の助けになればと思います。
外部から参照されることなく、またイミュータブルなものがほしいとき、

class Something {
    private $age = '永遠の17歳';

    public function changeAge(): void
    {
        $this->age = '30歳';
    }
}

外部からは参照できませんが内部から変更可能なので実装次第では変化してしまう可能性があります。

class Something {
    private function age(): string
    {
        return '永遠の17歳';
    }
}

private functionが値を返すことでイミュータブルが守られますが、個人的に好きではない。

っていうかそれ定数

class Something {
    private const AGE = '永遠の17歳';
}

PHP7.1からはconstのアクセス修飾子にprivateが書けるようになっていたので無事外部から参照されることなく、またイミュータブルなものが実現できました。
https://www.php.net/manual/ja/language.oop5.constants.php#language.oop5.basic.class.this

31
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
31
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?