search
HomeBackend DevelopmentPHP TutorialPHP5多态性与动态绑定介绍_PHP

什么是多态性?

多态性是继数据抽象和继承后,面向对象语言的第三个特征。从字面上理解,多态的意思是“多种形态”,简单来说,多态是具有表现多种形态的能力的特征,在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 是一种动态语言,使用动态绑定。无须考虑采取何种绑定策略,因为一起都是自动的。

Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.