萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP $this 關鍵字深度解析:物件內部存取的核心

什麼是 $this?

$this 是 PHP 物件導向中的特殊變數,代表當前實例化的物件本身。它只能在類別的非靜態方法內部使用,用於存取該物件的屬性(成員變數)與方法(成員函式)。

核心用法

1. 存取物件屬性

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

2. 呼叫物件內部其他方法

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

進階場景:建構子與複製行為

建構子中的 $this

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

區域變數 vs 物件屬性

方法內的區域變數不屬於物件,不可使用 $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

常見錯誤與除錯

  • 在靜態方法使用 $this:Fatal Error: Using $this when not in object context
  • 忘寫 $this 存取屬性:誤以為像 JavaScript 可直接用變數名
  • 建構子參數名與屬性名衝突:務必用 $this->name = $name 區分

總結

$this 是物件「自我參考」的核心機制,掌握其作用域(僅非靜態方法內)與指向性(指向當前實例),是寫出正確 PHP OOP 程式碼的基石。記住:屬性與方法必須加 $this->,區域變數絕不可加。

copyright © 萬盛學電腦網 all rights reserved