$this 是 PHP 物件導向中的特殊變數,代表當前實例化的物件本身。它只能在類別的非靜態方法內部使用,用於存取該物件的屬性(成員變數)與方法(成員函式)。
<?php
class User {
private $name;
public function __construct($name) {
// 區分區域變數 $name 與屬性 $this->name
$this->name = $name;
}
public function getName() {
return $this->name; // 必須使用 $this-> 存取屬性
}
}
$user = new User('Mike');
echo $user->getName(); // Mike
?>
<?php
class Calculator {
public function sum($a, $b) {
return $a + $b;
}
public function multiply($a, $b) {
return $a * $b;
}
public function calculate($a, $b, $c) {
// 使用 $this-> 呼叫同一物件的其他方法
$sum = $this->sum($a, $b);
return $this->multiply($sum, $c);
}
}
$calc = new Calculator();
echo "(2+3)*10 = " . $calc->calculate(2, 3, 10); // (2+3)*10 = 50
?>
<?php
class Person {
public $name;
public $sex;
public $age;
public function __construct($name = '', $sex = '', $age = '') {
// $this 代表正在建立的新物件
$this->name = $name;
$this->sex = $sex;
$this->age = $age;
}
public function say() {
echo "我的名字叫:{$this->name} 性別:{$this->sex} 年齡:{$this->age}<br>";
}
// 複製物件時自動呼叫
public function __clone() {
// $this 指向「新複製出來的物件(副本)」
$this->name = "我是副本的 {$this->name}";
$this->age = 30;
}
}
$p1 = new Person('張三', '男', 20);
$p2 = clone $p1; // 觸發 __clone()
$p1->say(); // 我的名字叫:張三 性別:男 年齡:20
$p2->say(); // 我的名字叫:我是副本的 張三 性別:男 年齡:30
?>
方法內的區域變數不屬於物件,不可使用 $this 存取:
<?php
class Example {
public $property = '屬性值';
public function method() {
$localVar = '區域變數'; // 只是區域變數
// echo $this->localVar; // 錯誤!區域變數無法用 $this 存取
echo $this->property; // 正確:存取物件屬性
}
}
?>
<?php
class UserName {
private $name;
public function __construct($name) {
$this->name = $name; // 使用 $this 指派屬性
}
public function __destruct() {
// 物件銷毀時自動呼叫
}
public function printName() {
print($this->name); // 使用 $this 讀取屬性
}
}
// 第一個物件
$nameObject = new UserName("heiyeluren");
$nameObject->printName(); // 輸出: heiyeluren
// 第二個物件(獨立實例,各自擁有 $this)
$nameObject2 = new UserName("PHP5");
$nameObject2->printName(); // 輸出:PHP5
?>
| 場景 | 是否使用 $this | 說明 |
|---|---|---|
| 存取物件屬性 | ✅ 必須 | $this->property |
| 呼叫物件方法 | ✅ 必須 | $this->method() |
| 建構子初始化 | ✅ 必須 | $this->prop = $value |
| 存取區域變數 | ❌ 禁止 | 直接用變數名 $var |
| 靜態方法內部 | ❌ 禁止 | 靜態方法無 $this,用 self:: 或 static:: |
| 全域函式 | ❌ 禁止 | 非類別方法無 $this |
Fatal Error: Using $this when not in object context$this->name = $name 區分$this 是物件「自我參考」的核心機制,掌握其作用域(僅非靜態方法內)與指向性(指向當前實例),是寫出正確 PHP OOP 程式碼的基石。記住:屬性與方法必須加 $this->,區域變數絕不可加。