PHP 7.4 で追加された Typed Property について
クラスのプロパティに型を指定できるようになります。
以下の例では $id は int ですが、string を入れようとしているために「Uncaught TypeError: Cannot assign string to property User::$id of type int」というエラーになります。
<?php
class User {
public int $id;
public string $name;
}
$user = new User;
$user->id = 'hoge'; // $id は int でないといけないが、string を入れようとしているので、Uncaught TypeError: Cannot assign string to property User::$id of type int になる
var_dump($user->id);
?>
PHPなので実行時にエラーになります。
最近のコメント