クラスの基本 / コンストラクタで初期化する / 演習 01

📝 ドリル 01 — コンストラクタで初期化する

問題

User クラスを定義してください。

  • public string $name;
  • public int $age;
  • public function __construct(string $name, int $age) で 2 つのプロパティを初期化する

new User("太郎", 20)1 行で インスタンスを作り、nameage を 1 行ずつ出力してください。

期待される出力:

太郎
20

採点

php scripts/grade.php v2/topics/08-class/ch06-constructor/drill/01-init/

ヒント

  • メソッド名は __construct (アンダースコア 2 つ)
  • $this->name = $name; $this->age = $age; の 2 行で初期化
  • 呼び出しは $u = new User("太郎", 20);1 行 で完結

テストケース

期待される出力

太郎
20

📄 starter.php(雛形)

このコードから書き始めてください。

<?php

// TODO:
//   1. User クラスを定義する
//        public string $name;
//        public int    $age;
//        public function __construct(string $name, int $age) {
//            // $this->name と $this->age を初期化
//        }
//   2. $u = new User("太郎", 20); で 1 行で生成する
//   3. name → age の順で 1 行ずつ出力する
✅ 解答例を見る(自分で解いてから)
<?php

class User {
    public string $name;
    public int $age;

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

$u = new User("太郎", 20);

echo $u->name . "\n";
echo $u->age . "\n";