购买
下载掌阅APP,畅读海量书库
立即打开
畅读海量书库
扫码下载掌阅APP

2.10 多态性

多态性是建立几个具体的父类对象的过程。拿上面的例子来说,我们创建了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关键字,用它来判断当前对象的父类关系。现在我们执行上面的脚本,会出现类似下面的输出结果: LyQJT2PCw/YYt4eKMIk3b0XSfCtsMo5trCARG2TI3jGP06dWv31o+SqzWIu2ISdz


Extended Emailer is Derived from Emailer.
HTML Emailer is also Derived from Emailer.

点击中间区域
呼出菜单
上一章
目录
下一章
×