在 PHP 類別內部,$this 是指向「目前實例化物件」的特殊參考。它只能出現在非靜態成員方法中,用於存取同一物件的屬性與方法,解決區域變數與成員屬性同名時的命名衝突。
$this->property$this->method()$var,不可 加 $this->$this(因無實例上下文)class User {
private $name;
public function __construct($name) {
$this->name = $name; // 寫入屬性
}
public function greet() {
echo "Hello, " . $this->name; // 讀取屬性
}
}
$user = new User('Alice');
$user->greet(); // Hello, Alice
class Calculator {
public function add($a, $b) { return $a + $b; }
public function mul($a, $b) { return $a * $b; }
public function compute($a, $b, $c) {
$sum = $this->add($a, $b); // 呼叫同類別其他方法
return $this->mul($sum, $c);
}
}
echo (new Calculator())->compute(2, 3, 10); // (2+3)*10 = 50
class Person {
public $name;
public function __construct($name) { $this->name = $name; }
public function __clone() {
$this->name = 'Clone of ' . $this->name; // $this 指向新複製體
}
}
$p1 = new Person('Bob');
$p2 = clone $p1;
echo $p2->name; // Clone of Bob
class Demo {
public $value = 'member';
public function test() {
$value = 'local'; // 區域變數
echo $value; // 輸出 local
echo $this->value; // 輸出 member
}
}
class QueryBuilder {
private $sql = '';
public function select($fields) { $this->sql .= "SELECT $fields"; return $this; }
public function from($table) { $this->sql .= " FROM $table"; return $this; }
public function where($cond) { $this->sql .= " WHERE $cond"; return $this; }
public function getSQL() { return $this->sql; }
}
$sql = (new QueryBuilder())->select('*')->from('users')->where('id=1')->getSQL();
// SELECT * FROM users WHERE id=1
| 錯誤情境 | 錯誤訊息 | 修正方式 |
|---|---|---|
| 靜態方法中用 $this | Using $this when not in object context | 改用 self:: 或 static::,或移除 static 關鍵字 |
| 函式外部使用 $this | $this 只能在類別方法中使用 | 確保程式碼在 class 內部 |
| 未實例化直接呼叫方法 | Call to member function on null | 先 new 物件再呼叫 |
$this 是 PHP 物件導向的核心,掌握其作用域與生命週期,能寫出更清晰、可維護的類別設計。記住:有物件才有 $this,靜態脈絡裡看不到 $this。