Table of Contents
本篇文章探索 PHP 中 $this、self 和 parent 這三個關鍵字。這些關鍵字在物件導向程式設計(Object-Oriented Programming,簡稱 OOP)中有著重要的角色,正確地理解和使用它們對於寫出高品質的 PHP 程式碼有著不可或缺的影響。
物件導向程式設計是一種程式設計範例,它使用 “物件” — 將資料和功能方法封裝起來的一種設計方式。
您可能有興趣:PHP 物件導向的基礎,從類別 (Class) 與物件 (Object) 開始
物件程式範例
// 定義一個 'Car' 類別
class Car {
    // 資料
    public $brand;
    public $model;
    // 方法
    public function getInfo() {
        return $this->brand . ' ' . $this->model;
    }
}什麼是 PHP $this
基本概念
$this 在 PHP 的物件導向程式設計中指的是當前的實例(即物件)。它主要用於從類別的內部訪問自己的屬性和方法。
$this 代表物件自己。當在一個類別(Class)內部使用 $this 關鍵字,實際上是指向這個類別實例化(Instantiate)後產生的物件。
使用 $this 可以讓您輕鬆地在同一個物件的不同方法間共享數據。這提供了一個動態的方式來操作物件的狀態。
可以用 $this->屬性名稱 來存取該物件的屬性,或者用 $this->方法名稱() 來調用該物件的方法。
程式範例
class Car {
    public $color;
    public function describe() {
        return "This car is " . $this->color;  // 使用 $this 來訪問 color 屬性
    }
}
$myCar = new Car();
$myCar->color = 'red';
echo $myCar->describe();  // 輸出:This car is red什麼是 PHP self
基本概念
self 是一個特殊的關鍵字,用於在類別內部引用自己。主要用於訪問靜態屬性和靜態方法。
程式範例
class Circle {
    const PI = 3.14159;
    public static function area($radius) {
        return self::PI * $radius * $radius;
    }
}什麼是 PHP parent
基本概念
parent 用於從子類別中訪問父類別的方法。這主要在覆寫父類別的方法時用到。
當您需要使用並擴展父類別的功能時,parent 是很有用的。
有時,子類別需要擴展或定製父類別的功能而不是完全替換它。這時,使用 parent 可以非常有效地實現這一點。
通常用法是 parent::方法名稱()。
程式範例
class Animal {
    public function greet() {
        return "Hello, I'm an animal.";
    }
}
class Dog extends Animal {
    public function greet() {
        return parent::greet() . " And I'm also a dog.";  // 使用 parent 來調用父類別的 greet 方法
    }
}
$dog = new Dog();
echo $dog->greet();  // 輸出:Hello, I'm an animal. And I'm also a dog.$this、self 和 parent 的綜合應用
在 OOP 中,繼承和多型是兩個非常重要的概念,這些關鍵字在這些高級概念中也有著不可或缺的角色。
程式範例
<?php
class Animal {
    public function greet() {
        return "Hello, I'm an animal.";
    }
}
class Dog extends Animal {
    public function greet() {
        return "Woof! Woof!";
    }
    public function parentGreet() {
        return parent::greet();  // 使用 parent 關鍵字
    }
    public static $type = 'Mammal';
    public static function getType() {
        return self::$type;  // 使用 self 關鍵字
    }
    public function instanceGreet() {
        return $this->greet();  // 使用 $this 關鍵字
    }
}
// 實例化 Dog 類別
$dog = new Dog();
echo $dog->instanceGreet();  // 輸出 "Woof! Woof!"
echo $dog->parentGreet();    // 輸出 "Hello, I'm an animal."
echo Dog::getType();         // 輸出 "Mammal"
?>總結
本文介紹了 PHP 的 this、self 和 parent 這三個關鍵字,包括它們的基本概念、用途,以及如何在程式碼中正確地使用它們。透過理解這些關鍵字和它們的運用,將能更深入地掌握 PHP 和物件導向程式設計。
相關參考教學:






