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); // 兩個參數
?>
官方不建議常規使用,僅供特殊情境。
parent::方法名() 呼叫父類別實作。<?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(){ ... } // 錯誤:權限縮小 }