多态性是建立几个具体的父类对象的过程。拿上面的例子来说,我们创建了3个类,Emailer、ExtendedEmailer和HtmlEmailer,如代码清单2-13所示:
代码清单2-13 一个类的多次实现
<?php include("class.emailer.php"); include("class.extendedemailer.php"); include("class.htmlemailer.php"); $emailer = new Emailer("info@21cto.com"); $extendedemailer = new ExtendedEmailer(); $htmlemailer = new HtmlEmailer("hasin@somewherein.net"); //判断此对象是否属某个类 if ($extendedemailer instanceof emailer ){ echo "Extended Emailer is Derived from Emailer.<br/>"; } if ($htmlemailer instanceof emailer ){ echo "HTML Emailer is also Derived from Emailer.<br/>"; } if ($emailer instanceof htmlEmailer ){ echo "Emailer is Derived from HTMLEmailer.<br/>"; } if ($htmlemailer instanceof extendedEmailer ){ echo "HTML Emailer is Derived from Emailer.<br/>"; }?>
注意:我们使用了instantof关键字,用它来判断当前对象的父类关系。现在我们执行上面的脚本,会出现类似下面的输出结果:
Extended Emailer is Derived from Emailer. HTML Emailer is also Derived from Emailer.