從 JavaScript 轉向 PHP 開發時,常忽略 $this 關鍵字導致無法呼叫私有方法。本文透過實例說明 $this 在類別內部的必要性、可見性規則與常見錯誤。
<?php
class Person {
// 公有方法:對外介面
public function say(string $name, int $age): void {
// 關鍵:必須使用 $this-> 呼叫私有方法
$concatenated = $this->get($name, $age);
echo "My name is: {$name}
";
echo "My age is: {$age}
";
echo "Concatenated: {$concatenated}
";
}
// 私有方法:內部邏輯封裝
private function get(string $a, int $b): string {
return $a . $b;
}
}
// 使用
$person = new Person();
$person->say("Allen", 25);
// 輸出:
// My name is: Allen
// My age is: 25
// Concatenated: Allen25
?>
<?php
class Person {
public function say($name, $age) {
// 錯誤:漏寫 $this->
$con = get($name, $age); // Fatal Error: Call to undefined function get()
// 或嘗試靜態呼叫
$con = self::get($name, $age); // Fatal Error: Non-static method cannot be called statically
}
private function get($a, $b) {
return $a . $b;
}
}
?>
| 修飾符 | 類別內部 | 繼承類別 | 外部實例 |
|---|---|---|---|
| public | ✓ | ✓ | ✓ |
| protected | ✓ | ✓ | ✗ |
| private | ✓ | ✗ | ✗ |
get(),this 隱性綁定$this->、self::、parent:: 或 static::<?php
class Config {
private static $cache = [];
public static function get(string $key): mixed {
// 靜態方法內呼叫靜態私有方法/屬性
return self::$cache[$key] ?? self::load($key);
}
private static function load(string $key): mixed {
// 載入邏輯
return "value_for_$key";
}
}
?>
$this-> (非靜態) 或 self:: (靜態)$thisphpstan、psalm 可捕獲此類錯誤private,需要繼承才 protected,對外介面才 public