PHP5多态性与动态绑定介绍_PHP

WBOY
Release: 2016-05-30 14:59:19
Original
905 people have browsed it

什么是多态性?

多态性是继数据抽象和继承后,面向对象语言的第三个特征。从字面上理解,多态的意思是“多种形态”,简单来说,多态是具有表现多种形态的能力的特征,在OO中是指“语言具有根据对象的类型以不同方式处理之,特别是重载方法和继承类这种形式”的能力。多态被认为是面向对象语言的必备特性。

例如:

我们创建一个接口 Shape,定义一个空的方法 draw(),那么所有的实现类都必须实现这个方法,假设 Shape 有两个实现类:Triangle 和 Rectangle,我们虽然无法通过类似这样的 Java 代码来诠释 PHP 的多态性:

代码如下:


Shape s = new Triangle();
s.draw();


不过 PHP5.1 中引入了 Type Hinting,可以限制函数(或者方法)的参数类型,我们使用这个特性来演示 PHP5 的多态性。

参考如下的代码:

代码如下:


class TestPolymorphism {
    public function drawNow(Shape $shape) {
        $shape->draw();
    }
}


函数 drawNow() 中限制传入的参数类型必须为 Shape 接口派生类的对象,这里我们传递给 drawNow() 的参数可能是 Triangle 或者 Rectangle 的对象,也可能是其它的 Shape 接口的派生类对象,比如 Circle 等等,简单的说 drawNow() 的参数类型是无法预知的,$shape->draw() 的行为最终由传入的参数的具体类型来决定,比如如果传入 Triangle 的对象,那么就调用 Triangle 的 draw() 方法,如果传入 Rectangle 的对象,就调用 Rectangle 的 draw() 方法。这种在运行时刻根据传递的对象参数的类型来决定调用哪一个对象的方法的行为就可以称之为多态。

Shape 也可以是一个抽象基类或者是非抽象的基类,上面的论述都是成立的。区别在于接口仅定义一套实现类必须遵守的规则,而使用基类则可以为派生类提供一些缺省的行为。

参考代码如下:

代码如下:


/**
 * Shape Interface
 *
 * @version 1.0
 * @copyright
 */
interface Shape {
    public function draw();
}
 
/**
 * Triangle
 *
 * @uses Shape
 * @version 1.0
 * @copyright
 */
class Triangle implements Shape {  
    public function draw() {
        print "Triangle::draw()\n";
    }
}
 
/**
 * Rectangle
 *
 * @uses Shape
 * @version 1.0
 * @copyright
 */
class Rectangle implements Shape {
    public function draw() {
        print "Rectangle::draw()\n";
    }
}
 
/**
 * Test Polymorphism
 *
 * @version 1.0
 * @copyright
 */
class TestPoly {
    public function drawNow(Shape $shape) {
        $shape->draw();
    }
}
 
 
$test = new TestPoly();
$test->drawNow(new Triangle());
$test->drawNow(new Rectangle());
 
/* vim: set expandtab tabstop=4 shiftwidth=4: */

什么是动态绑定?

HaoHappy 翻译的 PHP5 Object Pattern 第九节中有介绍:

除了限制访问,访问方式也决定哪个方法将被子类调用或哪个属性将被子类访问。 函数调用与函数本身的关联,以及成员访问与变量内存地址间的关系,称为绑定。

另有的说法:

绑定(binding):将方法的调用连到方法本身被称为绑定,当绑定发生在编译期,被称做静态绑定,而在程序运行的时候根据对象的类型来决定该绑定方法的成为动态绑定。

PHP 是一种动态语言,使用动态绑定。无须考虑采取何种绑定策略,因为一起都是自动的。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!