Home php教程 php手册 深入php多态的实现详解

深入php多态的实现详解

Jun 13, 2016 am 11:49 AM
php superior function Can Polymorphism polymorphism accomplish object operate go deep of type Detailed explanation process

多态性是指相同的操作或函数、过程可作用于多种类型的对象上并获得不同的结果。不同的对象,收到同一消息将可以产生不同的结果,这种现象称为多态性。

多态性允许每个对象以适合自身的方式去响应共同的消息。多态性增强了软件的灵活性和重用性。

在面向对象的软件开发中,多态性是最为重要的部分之一。面向对象编程并不只是将相关的方法与数据简单的结合起来,而是采用面向对象编程中的各种要素将现实生活中的各种情况清晰的描述出来。这一小节将对面向对象编程中的多态性作详细的讲解。

1.什么是多态
 
多 态(Polymorphism)按字面上意思理解就是“多种形状”。可以理解为多种表现形式,也即“一个对外接口,多个内部实现方法”。在面向对象的理论 中,多态性的一般定义为:同一个操作作用于不同的类的实例,将产生不同的执行结果。也即不同类的对象收到相同的消息时,将得到不同的结果。

在实际的应用开发中,采用面向对象中的多态主要在于可以将不同的子类对象都当作一个父类来处理,并且可以屏蔽不同子类对象之间所存在的差异,写出通用的代码,做出通用的编程,以适应需求的不断变化。

2.多态的应用设计
 
在实际的应用开发中,通常为了使项目能够在以后的时间里的轻松实现扩展与升级,需要通过继承实现可复用模块进行轻松升级。在进行可复用模块设计时,就需要尽可能的减少使用流程控制语句。此时就可以采用多态实现该类设计。

【示例】例举了通常采用流程控制语句实现不同类的处理。其代码如下所示。

复制代码 代码如下:


    class painter{                                    //定义油漆工类
        public function paintbrush(){                 //定义油漆工动作
            echo "油漆工正在刷漆!/n";
        }
    }
    class typist{                                    //定义打字员类
        public function typed(){                     //定义打字员工作
            echo "打字员正在打字!/n";
        }
    }
    function printworking($obj){                    //定义处理类
        if($obj instanceof painter){                //若对象是油漆工类,则显示油漆工动作
            $obj->paintbrush();
        }elseif($obj instanceof typist){            //若对象是打字员类,则显示打字员动作
            $obj->typed();
        }else{                                    //若非以上类,则显示出错信息
            echo "Error: 对象错误!";
        }
    }
    printworking(new painter());                    //显示员工工作
    printworking(new typist());                     //显示员工工作
?>


分析:在上述程序中,首先定义两个员工类:油漆工类和打字员类。然后定义一个处理函数,在该函数中,判断员工是否为已经定义的员工,打印出员工的工作状态。其结果如下所示。
油漆工正在刷漆 
打字员正在打字
从 以上程序可轻松看出,若想显示其几种员工的工作状态,需要首先定义该员工类,并在该员工类中定义员工的工作,然后在printworking()函数中增 加elseif语句以检查对象是哪一员工类的实例。这在实际的应用中,是非常不可取的。若此时采用多态,则可以轻松解决此问题。

可以首先创建一个员工父类,所有的员工类将继承自该员工父类,并且继承父类的所有方法与属性。然后在员工类中创建“是一”关系,判断是否为合法的员工。

【示例】例举了采用多态的方式改写上例。其代码如下所示。

复制代码 代码如下:


class employee{//定义员工父类
protected function working(){//定义员工工作,需要在子类的实现
echo "本方法需要在子类中重载!";
}
}
class painter extends employee{//定义油漆工类
public function working(){//实现继承的工作方法
echo "油漆工正在刷漆!/n";
}
}
class typist extends employee{//定义打字员类
public function working(){
echo "打字员正在打字!/n";
}
}
class manager extends employee{//定义经理类
public function working(){
echo "经理正在开会!";
}
}
function printworking($obj){//定义处理方法
if($obj instanceof employee){//若是员工对象,则显示其工作状态
$obj->working();
}else{//否则显示错误信息
echo "Error: 对象错误!";
}
}
printworking(new painter());//显示油漆工的工作
printworking(new typist());//显示打字员的工作
printworking(new manager());//显示经理的工作
?>


分析:在上述程序中,首先定义一个员工基类,并定义一个员工工作状态的方法。然后定义将继承自员工基类的三个员工类:油漆工类、打字员类和经理类。然后定义显示员工工作状态的方法。并在该方法中创建一个“是一”关系,用于判断是否为合法的员工。其结果如下所示。
油漆工正在刷漆!
打字员正在打字!
经理正在开会!
从上例可发现,无论增加多少个员工类,只需要实现自员工父类继承的该员工类和方法。而无须修改显示员工工作状态的方法printworking()。  
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

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

See all articles