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

PHP $this 關鍵字深度解析:物件導向中當前實例指標的核心機制

     編輯:PHP 相關知識

$this:物件實例的「身分證」

在 PHP 類方法中,$this 是指向**當前實例化物件**的特殊變數(偽變數)。它不是普通變數,不可賦值、不可引用、不可銷毀。

核心規則

  • 僅能在**非靜態方法**中使用。
  • 指向**呼叫該方法的具體物件實例**。
  • 每個實例擁有獨立的屬性狀態,$this->property 存取的是該實例的屬性。
  • 不可在靜態方法、函數、全域作用域中使用(會拋出 Error: Using $this when not in object context)。

經典範例:建構子與方法中的 $this

<?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
?>

關鍵觀念:$this 在「執行時」綁定

<?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 vs self vs static

關鍵字指向用途作用域
$this當前**實例**存取實例屬性/方法非靜態方法
self當前**類**(定義處)存取靜態屬性/常數/方法靜態/非靜態方法
static**實際調用類**(晚期靜態綁定)繼承場景下的靜態成員靜態/非靜態方法

常見錯誤與避坑

  • 靜態方法中使用 $this:
    class Foo {
        public static function bar() {
            echo $this->val; // Fatal Error
        }
    }
    
  • 閉包中直接用 $this(PHP 5.3):
    $obj = new class { public $x = 1; };
    $fn = function() { echo $this->x; }; // Error
    // PHP 5.4+ 可用
    $fn = function() { echo $this->x; };
    $fn->bindTo($obj)();
    
  • 靜態屬性誤用 $this:
    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 多型、繼承、流式介面、閉包綁定等進階特性的基石。

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