PHP5多态性与动态绑定方法

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

例如:app

    建立一个接口 Shape,定义一个空的方法 draw(),那么全部的实现类都必须实现这个方法,假设 Shape 有两个实现类:Triangle 和 Rectangle,咱们虽然没法经过相似这样的 Java 代码来诠释 PHP 的多态性:
ide

Shape s = new Triangle();
函数

s.draw();
.net


class TestPolymorphism {
翻译

    public function drawNow(Shape $shape) {
        $shape->draw();
    }
}//codego.net
code


    函数 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 第九节中有介绍:

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