$this 代表 當前類實例化後的具體對象實例。它只能在對象方法(非靜態方法)中使用,用於訪問該對象的屬性(非靜態)和方法。
<?php
class User {
public $name; // 實例屬性
public function __construct($name) {
$this->name = $name; // 構造函數中初始化
}
public function getName() {
return $this->name; // 內部訪問自身屬性
}
public function greet() {
echo "Hello, " . $this->getName() . "!"; // 內部調用自身方法
}
}
// 實例化兩個獨立對象
$user1 = new User('張三');
$user2 = new User('李四');
$user1->greet(); // 輸出: Hello, 張三!
// 此時 $this === $user1
$user2->greet(); // 輸出: Hello, 李四!
// 此時 $this === $user2
?>
| 場景 | $this 指向 | 說明 |
|---|---|---|
構造函數 __construct() | 正在創建的新對象 | 初始化屬性 |
實例方法 getName() | 調用該方法的對象 | $user1->getName() 時 $this === $user1 |
靜態方法 staticFunc() | 不可用(報錯) | 靜態方法屬於類,不屬於實例;用 self:: 或 static:: |
閉包綁定 Closure::bind() | 可手動綁定任意對象 | 高級用法,$closure = function() { return $this->name; }; $bound = Closure::bind($closure, $user1, 'User'); |
| 繼承子類調用父類方法 | 子類實例對象 | parent::method() 內的 $this 仍指向子類實例 |
class A {
public static function test() {
echo $this->name; // Fatal Error: Using $this when not in object context
}
}
修正:用 self::$staticProp 或傳入實例參數。
$this->prop:訪問實例屬性/方法(動態綁定,支持多態)。self::PROP:訪問類常量/靜態屬性/靜態方法(靜態綁定,編譯期解析)。static::PROP:靜態延遲綁定(PHP 5.3+),指向實際調用的類。$obj2 = $obj1 指向同一實例,$obj1->name = '新' 會影響 $obj2。需克隆用 clone $obj1。class QueryBuilder {
protected $sql = '';
public function select($fields) {
$this->sql .= "SELECT $fields ";
return $this; // 返回 $this 支持鏈式
}
public function from($table) {
$this->sql .= "FROM $table ";
return $this;
}
public function where($condition) {
$this->sql .= "WHERE $condition ";
return $this;
}
public function getSQL() {
return trim($this->sql);
}
}
$sql = (new QueryBuilder())
->select('id, name')
->from('users')
->where('status = 1')
->getSQL();
// SELECT id, name FROM users WHERE status = 1
$this 是對象實例的“自我引用”,只存在於實例上下文中。$this 協調自身狀態與行為。$this、self::、static:: 三者區別是掌握 PHP OOP 進階特性(多態、靜態綁定、Trait)的基石。