1、多態的介紹與優勢
多態性是繼抽象和繼承后,面向對象語言的第三個特征。從字面上理解,多態的意思是“多種形態”,簡單來說,多態是具有表現多種形態的能力的特征,在OO中是指“語言具有根據對象的類型以不同方式處理。
OOP的模式并不僅僅是把很多函數和功能集合起來,目的而是使用類,繼承,多態的方式描述我們生活中的一種情況。從而使得我們的代碼更具有“物”的意義。幫助我們減少一些重復性的代碼和條件語句的判斷。
2、運算符 :instanceof
PHP 一個類型運算符。instanceof 用來測定一個給定的對象是否來自指定的對象類。
class A { }
class B { }$thing = new A;if ($thing instanceof A) {echo 'A';
}
if ($thing instanceof B) {echo 'B';
}
?3、多態的簡單應用
interface myusb{function type();function alert();
}
class zip implements myusb{function type(){echo "2.0";}function alert(){echo "U盤";}
}
class mp3 implements myusb{function type(){echo "1.0";}function alert(){echo "MP3";}
}
class mypc{function pcusb($what){$what->type();echo "</br>";$what->alert();}
}
$p = new mypc();
$zip = new zip();
$mp3 = new mp3();
$p->pcusb($mp3);
?