首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 多態性:方法重載模擬與方法覆寫完整指南

     編輯:PHP 綜合知識

PHP 不支援傳統方法重載(同名不同參數),但可透過魔術方法 __call 模擬;方法覆寫則是多態的核心體現。

方法重載模擬(__call)

當呼叫不存在的方法時,自動觸發 __call($method, $args)。

<?php
class A {
    public function test1($p){ echo "一個參數"; }
    public function test2($p){ echo "兩個參數"; }
    function __call($method,$args){
        if($method=="test"){
            if(count($args)==1) $this->test1($args);
            elseif(count($args)==2) $this->test2($args);
        }
    }
}
$a=new A();
$a->test(1);      // 一個參數
$a->test(100,2);  // 兩個參數
?>

官方不建議常規使用,僅供特殊情境。

方法覆寫

規則

  1. 父類別與子類別方法名、參數列表完全一致。
  2. 子類別可用 parent::方法名() 呼叫父類別實作。
  3. 存取修飾符範圍必須 ≥ 父類別(public ≥ protected ≥ private)。

範例:動物叫聲

<?php
class Animal { public function cry(){ echo "父類別未定義"; } }
class Dog extends Animal { public function cry(){ echo "狗汪汪叫!"; } }
class Pig extends Animal {
    public function cry(){
        echo "豬哼哼叫!<br/>";
        parent::cry(); // 呼叫父類別
    }
}
$dog=new Dog(); $dog->cry();
$pig=new Pig(); $pig->cry();
?>

存取修飾符限制示範

class Animal { public function cry(){ ... } }
class Dog extends Animal { protected function cry(){ ... } // 錯誤:權限縮小 }
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved