PHP 通過類、接口、Traits 等語言結構支持面向對象編程,同時提供豐富的內置函數與反射 API,實現運行時類型檢查、動態調用等高級特性。本文系統梳理 PHP OOP 的三大核心工具集。
魔術方法以雙下劃線 __ 開頭,在特定場景自動觸發,無需顯式調用。
function __autoload($className) {
require $className . '.class.php';
}
$demo = new Computer(); // 自動引入 Computer.class.php
現代最佳實踐:使用 spl_autoload_register() 註冊多個加載器,符合 PSR-4 標準,避免 __autoload 單一限制。
class Computer {
public function __call($method, $args) {
echo "方法 {$method} 不存在,參數: ";
print_r($args);
}
}
$computer->go('我', 1, '知道'); // 輸出: 方法 go 不存在,參數: Array ( [0] => 我 [1] => 1 [2] => 知道 )
適用於動態代理、委派模式、流式接口構建。
class Computer {
public function __toString() {
return 'Computer Object';
}
}
echo new Computer(); // 直接輸出對象字符串表示
未實現時直接 echo $obj 會拋出 E_RECOVERABLE_ERROR。
class Computer {
public $name;
public function __clone() {
$this->name = 'ibm'; // 修改克隆副本屬性
}
}
$c1 = new Computer(); $c1->name = 'dell';
$c2 = clone $c1;
echo $c2->name; // ibm
默認淺拷貝,引用類型屬性指向同一實例;__clone 可實現深拷貝邏輯。
__construct() / __destruct():構造/析構__get() / __set() / __isset() / __unset():屬性重載__sleep() / __wakeup():序列化控制__invoke():對象作為函數調用__set_state():var_export() 導出還原__debugInfo():var_dump() 輸出自定義這組函數僅能訪問 public 成員,適合第三方庫集成、插件系統等場景。
| 函數 | 功能 | 示例 |
|---|---|---|
class_exists() | 檢查類是否存在 | class_exists('Computer') |
get_class() | 獲取對象類名 | get_class($computer) |
get_class_methods() | 獲取類所有 public 方法 | get_class_methods($computer) |
get_class_vars() | 獲取類所有 public 屬性 | get_class_vars('Computer') |
get_parent_class() | 獲取父類名 | get_parent_class('NoteComputer') |
interface_exists() | 檢查接口是否存在 | interface_exists('Computer') |
is_a() | 對象是否為類/父類實例 | is_a($computer, 'Computer') |
is_subclass_of() | 對象是否為類的子類 | is_subclass_of($note, 'Computer') |
method_exists() | 檢查方法是否存在 | method_exists($computer, '_run') |
反射 API (ReflectionClass, ReflectionMethod 等) 可訪問 private/protected 成員、方法參數、註解等元數據,是框架開發、ORM、文檔生成的基石。
$rc = new ReflectionClass('Computer');
Reflection::export($rc); // 輸出完整結構:常量、屬性、方法、父類、接口等
Reflection::export(new ReflectionClass('Reflection'));
$rc = new ReflectionClass('Computer');
echo $rc->getFileName(); // 定義文件路徑
echo $rc->getName(); // 類名
// 更多:getMethods(), getProperties(), getConstants(), getDocComment() 等
ReflectionParameter::getClass() 解析構造函數參數類型提示,自動實例化依賴。@Route、@Validate 等 DocBlock 註解。註:本文內容整理自李炎恢 PHP 視頻教程,僅供學習交流,不可用於商業用途。
掌握這三大工具,讓你的 PHP OOP 代碼更靈活、更強大、更易擴展。