抽象方法僅聲明無實作(以分號結尾並加 abstract 修飾)。包含抽象方法的類別必須聲明為抽象類(abstract class)。抽象類不能實例化,需由子類繼承並實作所有抽象方法後才能建立對象。
abstract class Demo {
var $test;
abstract function fun1();
abstract function fun2();
function fun3() { /* 普通方法 */ }
}
class Test extends Demo {
function fun1() { /* 實作 */ }
function fun2() { /* 實作 */ }
}
$test = new Test(); // 正確
當調用對象不存在的方法時,PHP 會自動觸發 __call($method, $args) 魔術方法,避免程式報錯中斷。第一個參數為方法名,第二個為參數陣列。
class Test {
function __call($function_name, $args) {
print "你所調用的函數:$function_name(參數:";
print_r($args);
print ")不存在!\n";
}
}
$test = new Test();
$test->demo("one", "two", "three"); // 不會報錯,輸出提示
echo "this is a test"; // 程式繼續執行
clone 與 __clone()使用 clone 關鍵字可建立對象副本,兩者屬性相同但互不干擾。若需在克隆時修改副本屬性,可定義 __clone() 魔術方法。$this 指向副本,$that 指向原本(PHP 7.1+ 可用)。
class Person {
var $name, $sex, $age;
function __construct($name="", $sex="", $age="") {
$this->name=$name; $this->sex=$sex; $this->age=$age;
}
function say() { echo "我的名子叫:{$this->name} 性別:{$this->sex} 年齡:{$this->age}"; }
function __clone() {
$this->name = "我是假的{$that->name}"; // 修改副本屬性
$this->age = 30;
}
}
$p1 = new Person("張三", "男", 20);
$p2 = clone $p1;
$p1->say(); // 原本
$p2->say(); // 副本已修改