<?php //型を厳密にする declare(strict_types=1); class GameCharacter { //プロパティ private string $name; //名前 private int $level; //レベル private int $atttack; //攻撃力 private int $defense; //防御力 //コンストラクタ public function __construct(string $name, int $attack, int $defense) { //自分のクラスのプロパティは$thisという変数を使う $this ->name = $name; $this ->level = 1; $this ->attack = $attack; $this ->defense = $defense; } //メソッド(レベルアップ) //レベルアップすると攻撃力と防御力がランダム値上昇する public function levelUp(): void { //自分のクラスのメソッドにアクセスするには$thisを使う $this->level++; $this->attackUp(); $this->defenseUp(); } //メソッド(ステータス表示) public function echoStatus(): void { echo "{$this->name}はレベル{$this->level}で、攻撃力:{$this->attack}, 防御力:{$this->defense}\n"; } private function getRandomValue(): int { //<< 疑似乱数を生成する組み込み関数 //1から10のランダムの値を返す return random_int(1,10); } private function attackUp(): void { $up = $this->getRandomValue(); $this->attack += $up; echo "{$this->name}の攻撃力は{$up}上がった\n"; } private function defenseUp():void { $up = $this->getRandomValue(); $this->defense += $up; echo "{$this->name}の防御力は{$up}上がった\n"; } } $taro = new GameCharacter("Taro", 100, 90); // GameCharacterクラスをインスタンス化(実体化) $jiro = new GameCharacter("Jiro", 80, 110); // GameCharacterクラスをインスタンス化(実体化) $taro->levelUp(); //メソッド呼び出し $jiro->levelUp(); //メソッド呼び出し $taro->echoStatus(); $jiro->echoStatus(); //$taro->getRandomValue(); //privateメソッドのアクセスはエラー ?>
You have javascript disabled. You will not be able to edit any code.
Did not find `PhpShell_Output` with id `199644435`