在 PHP 類方法中,$this 是指向**當前實例化物件**的特殊變數(偽變數)。它不是普通變數,不可賦值、不可引用、不可銷毀。
$this->property 存取的是該實例的屬性。Error: Using $this when not in object context)。<?php
class UserName {
private $name;
public function __construct($name) {
// 此時 $this 指向正在建構的新實例
$this->name = $name;
}
public function printName() {
// $this 指向呼叫 printName() 的那個實例
print($this->name);
}
}
// 實例化第一個物件
$nameObject = new UserName("heiyeluren");
// 內部:$this->name = "heiyeluren"
$nameObject->printName(); // 輸出:heiyeluren
// 此時 $this 等同於 $nameObject
// 實例化第二個物件
$nameObject2 = new UserName("PHP5");
// 內部:$this->name = "PHP5"
$nameObject2->printName(); // 輸出:PHP5
// 此時 $this 等同於 $nameObject2
?>
<?php
class A {
public $val = 'A';
public function who() { echo $this->val; }
}
class B extends A {
public $val = 'B';
}
$a = new A();
$b = new B();
$a->who(); // 輸出 A($this 綁定 $a)
$b->who(); // 輸出 B($this 綁定 $b)
// 甚至可以動態綁定(Closure::bindTo)
$closure = function() { echo $this->val; };
$boundToA = $closure->bindTo($a, A::class);
$boundToB = $closure->bindTo($b, B::class);
$boundToA(); // A
$boundToB(); // B
?>
| 關鍵字 | 指向 | 用途 | 作用域 |
|---|---|---|---|
$this | 當前**實例** | 存取實例屬性/方法 | 非靜態方法 |
self | 當前**類**(定義處) | 存取靜態屬性/常數/方法 | 靜態/非靜態方法 |
static | **實際調用類**(晚期靜態綁定) | 繼承場景下的靜態成員 | 靜態/非靜態方法 |
class Foo {
public static function bar() {
echo $this->val; // Fatal Error
}
}
$obj = new class { public $x = 1; };
$fn = function() { echo $this->x; }; // Error
// PHP 5.4+ 可用
$fn = function() { echo $this->x; };
$fn->bindTo($obj)();
class Counter {
private static $count = 0;
public function inc() {
$this->count++; // 錯誤:建立實例屬性 $count,非靜態 $count
self::$count++; // 正確
}
}
<?php
class QueryBuilder {
private $parts = [];
public function select(string $fields): self {
$this->parts['select'] = $fields;
return $this; // 回傳 $this 支援鏈式呼叫
}
public function where(string $cond): self {
$this->parts['where'] = $cond;
return $this;
}
public function getSql(): string {
return "SELECT {$this->parts['select']} FROM table WHERE {$this->parts['where']}";
}
}
$sql = (new QueryBuilder())
->select('id, name')
->where('id > 10')
->getSql();
// SELECT id, name FROM table WHERE id > 10
?>
$this 是 PHP 物件導向的核心綁定機制,代表「執行此方法的那個具體物件」。理解 $this 的**執行時綁定**特性,區分 self/static 的**編譯時/晚期綁定**,是掌握 PHP 多型、繼承、流式介面、閉包綁定等進階特性的基石。