Hi! Could we please enable some services and cookies to improve your experience and our website?

PHPize Online / SQLize Online  /  SQLtest Online

A A A
Login    Share code      Blog   FAQ

Online Sandbox for SQL and PHP: Write, Run, Test, and Share SQL Queries and PHP Code

Copy Format Clear

Stuck with a problem? Got Error? Ask AI support!

Copy Clear
Copy Format Clear
<?php class Athlete { /* ===== 權限示範 ===== */ protected int $stamina; // 子類別可直接調整 private float $salary; // 僅 Athlete 內部知道 protected string $name; // 延續舊範例 protected int $age; public function __construct(string $name, int $age, float $salary) { $this->name = $name; $this->age = $age; $this->salary = $salary; $this->stamina = 100; // 初始體能 } /* ===== public 介面 ===== */ public function train(): void { // 公開方法可使用 private $salary(在本類別裡合法) $this->decreaseStamina(10); printf("%s 訓練 1 小時,體能剩餘 %d%%,月薪 %.1f 萬\n", $this->name, $this->stamina, $this->salary); } protected function playGame(): void { printf("playgame"); } /* ===== protected 工具 ===== */ // 子類別可以呼叫以消耗或回復體能 protected function decreaseStamina(int $point): void { $this->stamina = max(0, $this->stamina - $point); } protected function recover(): void { $this->stamina = 100; } } /* ---------- 子類別 ---------- */ class VolleyballPlayer extends Athlete { // 覆寫,不同項目有不同玩法 public function playGame(): void { // 直接操作 protected $stamina $this->decreaseStamina(30); printf("%s 扣殺得分!體能剩 %d%%\n", $this->name, $this->stamina); } // 額外公開方法示範 public function rest(): void { $this->recover(); printf("%s 休息完畢,體能回復到 %d%%\n", $this->name, $this->stamina); } } class BaseballPlayer extends Athlete { public function __construct(string $name, int $age, float $salary, public string $position) { parent::__construct($name, $age, $salary); } // 覆寫,不同項目有不同玩法 public function playGame(): void { $this->decreaseStamina(20); printf("%s (%s) 上場投球,體能剩 %d%%\n", $this->name, $this->position, $this->stamina); } } $players = [ new VolleyballPlayer('小李', 23, 6.5), new BaseballPlayer ('小王', 26, 12.0, 'Pitcher'), ]; foreach ($players as $p) { $p->train(); // 父類別公開方法 $p->playGame(); // 多型 echo "-----\n"; }
Copy Clear