| 機制 | 適用場景 | 語法 |
| instanceof 運算子 | 運行期動態檢查,條件判斷分支 | $obj instanceof ClassName |
| 型別提示 | 方法簽章強制約束,編譯期/載入期檢查 | function foo(MyClass $obj) |
反面教材:缺乏型別檢查的風險
<?php
abstract class HTMLElement {
protected $attributes;
protected function __construct($attributes) {
if (!is_array($attributes)) throw new Exception('Invalid attribute type');
$this->attributes = $attributes;
}
abstract protected function getHTML();
}
class Div extends HTMLElement { /* ... 實作 getHTML() ... */ }
class Header1 extends HTMLElement { /* ... */ }
class Paragraph extends HTMLElement { /* ... */ }
class UnorderedList extends HTMLElement { /* ... */ }
// 頁面產生器 - 未檢查元素型別
class PageBuilder {
private $elements = array();
public function addElement($element) { // 危險:接受任意型別
$this->elements[] = $element;
}
public function render() {
foreach ($this->elements as $el) {
echo $el->getHTML(); // 若 $el 非 HTMLElement 子類,致命錯誤
}
}
}
?>
正確做法:instanceof 守衛
<?php
class PageBuilder {
private $elements = array();
public function addElement($element) {
if (!($element instanceof HTMLElement)) {
throw new InvalidArgumentException('Element must be HTMLElement instance');
}
$this->elements[] = $element;
}
// ...
}
// 型別提示版(PHP 5.0+)
class PageBuilder {
public function addElement(HTMLElement $element) { // 自動檢查
$this->elements[] = $element;
}
}
?>
進階用法
$obj instanceof InterfaceName 檢查介面實作
$obj instanceof $className 變數儲存類別名動態檢查
- 搭配
ReflectionClass 進行深度型別分析
效能考量
instanceof 為內建運算子,極快(納秒級)。大量檢查場景可考慮快取 ReflectionClass 結果或使用型別提示(零運行期開銷)。
- 上一篇文章: PHP 呼叫 Java 類別操作資料庫:跨語言整合實戰架構
- 下一篇文章: PHP zlib 擴充套件實現 GZIP 頁面壓縮輸出:提升傳輸效能 70%+
Copyright ©
程式碼之家 All Rights Reserved