物件導向程式設計(OOP)是現代 PHP 開發的核心範式,能讓程式碼更具模組化、可維護性與擴充性。本文將系統性介紹 PHP 中 OOP 的核心概念、語法實作與進階技巧,幫助開發者掌握從類別定義到設計模式的完整知識體系。
PHP 物件導向建立在三大支柱之上:
<?php
class User {
// 屬性宣告(建議加上型別宣告與存取修飾詞)
private string $name;
private int $age;
// 建構子
public function __construct(string $name, int $age) {
$this->name = $name;
$this->age = $age;
}
// 存取器
public function getName(): string {
return $this->name;
}
public function getAge(): int {
return $this->age;
}
// 方法
public function greet(): string {
return "Hello, I'm {$this->name}, {$this->age} years old.";
}
}
?>
<?php
$user = new User('Alice', 25);
echo $user->greet(); // 輸出:Hello, I'm Alice, 25 years old.
?>
使用 extends 關鍵字實作繼承,子類別可覆寫父類別方法:
<?php
class Admin extends User {
private string $role;
public function __construct(string $name, int $age, string $role) {
parent::__construct($name, $age); // 呼叫父類別建構子
$this->role = $role;
}
// 覆寫方法
public function greet(): string {
return parent::greet() . " I'm an {$this->role}.";
}
}
$admin = new Admin('Bob', 30, 'Administrator');
echo $admin->greet();
?>
<?php
interface Loggable {
public function log(string $message): void;
}
class FileLogger implements Loggable {
public function log(string $message): void {
file_put_contents('app.log', $message . PHP_EOL, FILE_APPEND);
}
}
?>
<?php
abstract class BaseController {
protected function renderView(string $view, array $data = []): void {
extract($data);
include "views/{$view}.php";
}
abstract public function handleRequest(): void; // 強制子類別實作
}
?>
PHP 不支援多重繼承,Trait 解決橫向重用問題:
<?php
trait Timestampable {
private DateTime $createdAt;
private DateTime $updatedAt;
public function setTimestamps(): void {
$this->createdAt = new DateTime();
$this->updatedAt = new DateTime();
}
public function updateTimestamp(): void {
$this->updatedAt = new DateTime();
}
}
class Article {
use Timestampable;
// ...
}
?>
__construct() / __destruct():建構與解構__call() / __callStatic():處理不可存取的方法呼叫__get() / __set() / __isset() / __unset():屬性存取攔截__toString():物件轉字串__invoke():讓物件可像函式被呼叫__clone():複製物件時的自訂邏輯__sleep() / __wakeup():序列化控制<?php
class Config {
private static array $settings = [];
public static function set(string $key, $value): void {
self::$settings[$key] = $value;
}
public static function get(string $key, $default = null) {
return self::$settings[$key] ?? $default;
}
}
// 晚期靜態綁定(PHP 5.3+)
class Model {
public static function tableName(): string {
return static::TABLE; // 解析為實際呼叫的子類別常數
}
}
class User extends Model {
const TABLE = 'users';
}
echo User::tableName(); // 輸出:users
?>
<?php
class SessionData implements Serializable {
private array $data = [];
public function serialize(): string {
return serialize($this->data);
}
public function unserialize($data): void {
$this->data = unserialize($data);
}
public function __clone() {
// 深度複製邏輯
$this->data = array_map(fn($v) => is_object($v) ? clone $v : $v, $this->data);
}
}
?>
readonly 屬性、enum、match 運算式declare(strict_types=1))掌握 PHP 物件導向程式設計不僅能提升程式碼品質,更是建構大型可維護應用程式的基石。建議從實際專案中逐步應用上述概念,並持續精進設計模式與架構思維。