PHP の コンストラクタプロモーション

レベル 4206 打鍵

コンストラクタプロモーション(PHP 8.0)と readonly プロパティ(PHP 8.1)で User クラスを短く定義し、email を表示します。

PHP のコード

1class User {
// 引数に可視性キーワードを付けると、プロパティの宣言と代入が同時に行われる
2 public function __construct(
// readonly:値は一度だけ設定でき、その後は変更できない
3 public readonly string $name,
4 public readonly int $age,
5 public readonly string $email
// プロモーションがすべて行うので本体は空
6 ) {}
7}
8
// 引数は順に $name、$age、$email に代入される
9$user = new User("Alice", 25, "alice@example.com");
// 読み取りはできる。「alice@example.com」を表示する
10echo $user->email;

実行結果

alice@example.com
このコードでタイピング練習する

このコードでタイピング練習ができます。記録はランキングに反映されません。

このコードで使う記号

この PHP のコードで打つ記号と、出てくる回数です。

  • $× 5
  • ,× 4
  • "× 4
  • _× 2
  • ;× 2
  • (× 2
  • )× 2
  • {× 2
  • }× 2
  • -× 1

PHP のレベル 4 のほかのコード例

← PHP タイピング練習のトップへ