【PHP7.4】新機能に型付きプロパティ(Typed properties)が追加

PHP
スポンサーリンク

はじめに

本記事ではPHP7.4で追加された新機能の一つ、型付きプロパティ(Typed properties)を紹介します。

型付きプロパティ(Typed properties)

PHPは7.4でクラスのプロパティに型を宣言できるようになりました。
この型付きプロパティを、どのように使用するか確認します。

使用例

クラスのプロパティに型を宣言するときは、次のようにアクセス修飾子(本例ではprotected)と変数名の間に型を指定します。

<?php

class Human
{
    protected string $name;

    protected int $height;

    protected DateTime $birthday;

    /**
     * Human constructor.
     * @param string $name
     * @param int $height
     * @param DateTime $birthday
     */
    public function __construct(string $name, int $height, DateTime $birthday)
    {
        $this->name = $name;
        $this->height = $height;
        $this->birthday = $birthday;
    }

    public function changeHeight($height): void
    {
        $this->height = $height;
    }

}

正常に実行されるケース

上記のクラスを使用する例を用意しました。changeHeight()には引数にintの値を渡します。
Human::$heightはプロパティの方をintで宣言しているため、この処理はエラーにならず終了します。

function main() {
    $human = new Human('Blue', 170, new DateTime('2000-01-01'));
    $human->changeHeight(180);
}

main();

実行時エラーが発生するケース

次の例はchangeHeight()に文字列を渡しています。このとき、Human::$heightの型と引数の型が不一致となるため、実行時エラーが発生します。

function main() {
    $human = new Human('Blue', 170, new DateTime('2000-01-01'));
    $human->changeHeight('abc');
}

main();
PHP Warning:  Uncaught TypeError: Typed property Human::$height must be int, string used in php shell code:22
Stack trace:
#0 php shell code(4): Human->changeHeight('abc')
#1 php shell code(1): main()
#2 {main}
  thrown in php shell code on line 22

Warning: Uncaught TypeError: Typed property Human::$height must be int, string used in php shell code:22
Stack trace:
#0 php shell code(4): Human->changeHeight('abc')
#1 php shell code(1): main()
#2 {main}
  thrown in php shell code on line 22

参考

PHP: 新機能 - Manual