name = $name; $this->age = $age; $this->id = $id; } // 方法 public function getName(): string { return $this->name; } protected function setAge(int $age): void { if ($age > 0) $this->age = $age; } private function generateId(): string { return uniqid('uid_'); } }
| 關鍵字 | 類別內部 | 子類別 | 外部 |
|---|---|---|---|
| public | ✓ | ✓ | ✓ |
| protected | ✓ | ✓ | ✗ |
| private | ✓ | ✗ | ✗ |
$this->property$this->method()self::、static::、ClassName::。balance; } public function deposit(float $amount): bool { if ($amount <= 0) return false; $this->balance += $amount; return true; } public function withdraw(float $amount): bool { if ($amount <= 0 || $amount > $this->balance) return false; $this->balance -= $amount; return true; } } $acc = new BankAccount(); $acc->deposit(1000); $acc->withdraw(200); echo $acc->getBalance(); // 800
log('processing'); } }
null、array(常數陣列)、物件(PHP 8.1+ new Class())。
name; // 讀取 public 屬性
$p->name = 'Bob'; // 寫入 public 屬性
// 透過方法存取 protected/private
$p->setAge(30); // 呼叫 protected 方法(若在子類或同類內)
echo $p->getName(); // 呼叫 public 方法
PHP 5+ 完整支援物件導向三大特性:封裝(可見性)、繼承、多型。善用 private 隱藏內部狀態、protected 開放子類擴充、public 定義介面,配合型別提示與嚴格模式,能建構健壯可維護的類別體系。