PHP面向对象开发之类的多态详解
类的多态
1.多态的介绍和优势。
2.运算符:instanceof。
3.多态的简单应用。
1.多态的介绍和优势
介绍:多态性是继承抽象和继承后,面向对象语言的第三特征。
例子:USB接口,插上不同的东西会使用不同的功能。
优势:OOP并不仅仅是把很多函数和功能集合起来,目的而是使用类,继承,多态的方式描述我们生活中的一种情况。
2.运算符:instanceof
PHP一个类型运算符,用来测定一个给定的对象是否来自指定的对象
格式代码如下:
class A {}
class B {}
$thing = new A;
if ($thing instanceof A) {
echo "A";
}
if ($thing instanceof B) {
echo "B";
}3.多态的简单应用
实例1代码如下:
<?php
class A {
}
class B {
}
$new = new A;
if ($new instanceof A) {
echo "A";
}
if ($new instanceof B) {
echo "B";
}
?>实例2代码如下:
<?php
interface MyUsb {
function type();
function alert();
}
class Zip implements MyUsb {
function type() {
echo "2.0";
}
function alert() {
echo "U盘驱动正在检测……<br />";
}
}
class Mp3 implements MyUsb {
function type() {
echo "1.0";
}
function alert() {
echo "MP3驱动正在检测……";
}
}
class MyPc {
function Add_Usb($what) {
$what->type();
$what->alert();
}
}
$p = new MyPc();
$zip = new Zip();
$mp3 = new Mp3();
$p->Add_Usb($zip);
$p->Add_Usb($mp3);
?>补充一个实例代码:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>继承和多态</title>
</head>
<body>
<?php
/* 父类 */
class MyObject {
public $object_name; //图书名称
public $object_price; //图书价格
public $object_num; //图书数量
public $object_agio; //图书折扣
function __construct($name, $price, $num, $agio) { //构造函数
$this->object_name = $name;
$this->object_price = $price;
$this->object_num = $num;
$this->object_agio = $agio;
}
function showMe() { //输出函数
echo '这句话不会显示。';
}
}
/* 子类Book */
class Book extends MyObject { //MyObject的子类。
public $book_type; //类别
function __construct($type, $num) { //声明构造方法
$this->book_type = $type;
$this->object_num = $num;
}
function showMe() { //重写父类中的showMe方法
return '本次新进' . $this->book_type . '图书' . $this->object_num . '本<br>';
}
}
/* 子类Elec */
class Elec extends MyObject { //MyObject的另一个子类
function showMe() { //重写父类中的showMe方法
return '热卖图书:' . $this->object_name . '<br>原价:' . $this->object_price . '<br>特价:' . $this->object_price * $this->object_agio;
}
}
/* 实例化对象 */
$c_book = new Book('计算机类', 1000); //声明一个Book子类对象
$h_elec = new Elec('PHP函数参考大全', 98, 3, 0.8); //声明一个Elec子类对象
echo $c_book->showMe() . "<br>"; //输出Book子类的showMe()方法
echo $h_elec->showMe(); //输出Elec子类的是showMe()方法
?>
</body>
</html>本文地址:http://www.phprm.com/mxdx/fs1561.html
转载随意,但请附上文章地址:-)