首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 物件導向:$this 關鍵字完整用法指南

     編輯:PHP 相關知識

什麼是 $this?

在 PHP 類別內部,$this 是指向「目前實例化物件」的特殊參考。它只能出現在非靜態成員方法中,用於存取同一物件的屬性與方法,解決區域變數與成員屬性同名時的命名衝突。

核心規則速覽

  • 存取屬性:$this->property
  • 呼叫方法:$this->method()
  • 建構子中:代表正在被建立的新物件
  • 區域變數:方法內部直接用 $var,不可 加 $this->
  • 靜態方法中:禁止 使用 $this(因無實例上下文)

實戰範例

1. 基本屬性與方法存取

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

2. 方法鏈式呼叫

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

3. 複製物件時的 __clone 與 $this

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

4. 區域變數 vs 成員屬性同名

class Demo {
    public $value = 'member';
    public function test() {
        $value = 'local';           // 區域變數
        echo $value;                // 輸出 local
        echo $this->value;          // 輸出 member
    }
}

進階應用:鏈式風格與 Fluent Interface

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

常見錯誤與除錯提示

錯誤情境錯誤訊息修正方式
靜態方法中用 $thisUsing $this when not in object context改用 self:: 或 static::,或移除 static 關鍵字
函式外部使用 $this$this 只能在類別方法中使用確保程式碼在 class 內部
未實例化直接呼叫方法Call to member function on null先 new 物件再呼叫

總結

$this 是 PHP 物件導向的核心,掌握其作用域與生命週期,能寫出更清晰、可維護的類別設計。記住:有物件才有 $this,靜態脈絡裡看不到 $this。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved