Programming Design: Analysis of the implementation of polymorphism in PHP 5

Source: Internet
Author: User
Tags abstract date definition continue implement object model
Author: Zhu Xianzhong compilation

   Summary:This article will discuss the concept of polymorphism and its application in object-oriented design, and will also analyze how to use polymorphism in PHP 5 and its advantages and disadvantages.

Support for late binding has been implemented in the latest releases of PHP. Of course, there are a lot of problems when using its late-binding functionality. If you are using an older version of PHP (PHP 5.0.1 is running on my server), you may find that there is a lack of support for late binding. Therefore, please note that the code in this article may not work in your specific PHP 5 version.

   One, PHP 5 and polymorphism

This article wants to discuss one of the most important parts of object-oriented programming--the design of polymorphism. To illustrate the problem, I used PHP 5. Before you continue to read, please make it clear that this article is not entirely about PHP. Although this language has made great strides in rapid development in the previous two major editions, its support for objects goes a long way before it can match more mature languages like C + + or java.

If you're a beginner of object-oriented programming, this article may not be right for you, because polymorphism is a bit of a special knowledge: once you understand it, you'll never forget it. If you want to learn a little about object programming and design knowledge, and when someone says "an object is polymorphic," it's not quite clear what it means, then this article is right for you.
At the end of this article, you should know what polymorphism is and how to apply it to object-oriented design, and you will understand the advantages and disadvantages of object programming in PHP 5.

   second, what is polymorphism?

Polymorphism, which comes from the definition of dictionary.com, "appears in different forms, stages, or types in an independent organization, or in a homogeneous organization, without a fundamental distinction." "By this definition, we can argue that polymorphism is a programming way to describe the same object through a variety of states or stages." In fact, the real meaning of it is: in actual development, we only need to focus on an interface or base class programming, without worrying about the specific classes (class) that an object belongs to.

If you are familiar with design patterns, you will understand this concept even if you have a preliminary understanding. In fact, polymorphism may be the greatest tool in programming based on pattern design. It allows us to organize similar objects in a logical way so that we do not have to worry about the specific types of objects when we encode them, and we only need to program to one of the desired interfaces or base classes. The more abstract an application is, the more flexible it becomes--and polymorphism is one of the best ways to abstract behavior.

For example, let's consider a class called person. We can subclass a person with classes called David,charles and Alejandro. The person has an abstract method Acceptfeedback (), and all subclasses implement this method. This means that any code that uses a subclass of the base class person can Invoke Method Acceptfeedback (). You don't have to check if the object is a David or a Alejandro, just knowing that it is a person is enough. As a result, your code only needs to focus on the "lowest common denominator"-person class.

The person class in this example can also be created as an interface. Of course, there are some differences compared to the above, mainly because an interface does not give any behavior, but only the set of rules. A person interface requires that you must support the Addfeedback () method, while a person class can provide the default code for some Addfeedback () method-Your understanding can be "if you do not choose to support Addfeedback (), Then you should provide a default implementation. "As to how to select an interface or base class is not the subject of this article, but generally, you need to implement a default method through the base class." You can also use an interface if you can simply sketch out a set of desired features that your class is going to implement.

   third, the application of polymorphism design

We will continue to use the example of the person base class and now let us analyze the implementation of a non polymorphism. The following examples use different types of person objects-a very undesirable way of programming. Notice that the actual person class is omitted. So far, we're only concerned with code invocation issues.

$name = $_session[' name '];
$myPerson = Person::getperson ($name);
Switch (Get_class ($myPerson)) {
Case ' David ':
$myPerson->addfeedback (' Great article! ', ' Some Reader ', date (' y-m-d '));
Break
Case ' Charles ':
$myPerson->feedback[] = Array (' Some Reader ', ' great editing! ');
Break
Case ' Alejandro ':
$myPerson->feedback->append (' Awesome javascript! ');
Break
Default:
$myPerson->addfeedback (' yay! ');
}
? >

This example shows objects that behave differently, and a switch statement that distinguishes between different person class objects to perform their respective proper operations. Note that the feedback notes for different conditions are different here. This may not be the case in real-world application development; I just want to simply illustrate the differences that exist in class implementations.

The following example uses polymorphism.

$name = $_session[' name '];
$myPerson = Person::getperson ($name);
$myPerson->addfeedback (' Great article! ', ' Somereader ', date (' y-m-d '));
? >

Note that there are no switch statements, and most importantly, the lack of the type of object that Person::getperson () will return. and the other Person::addfeedback () is a polymorphic method. Behavior is encapsulated entirely by a specific class. Keep in mind that regardless of whether we are using David,charles or Alejandro, the calling code does not have to know the functionality of the specific class, but only the base class.

Although my example is not perfect, it shows the basic usage of polymorphism from the point of view of the calling code. Now we need to analyze the internal implementations of these classes. One of the great things that derive from a base class is that the derived class is able to access the behavior of the parent class, which is often the default implementation, but may also appear in the class inheritance chain to create more complex behavior. Here is a simple demonstration of this situation.

Class person{
function Addfeedback ($comment, $sender, $date) {
Adding feedback to the database
}
}
Class David extends person{
function Addfeedback ($comment, $sender) {
Parent::addfeedback ($comment, $sender,
Date (' y-m-d '));
}
}
? >

In this case, the Person::addfeedback method is first invoked in the Addfeedback method implementation of the David class. As you may notice, it mimics the method overloads in C++,java or C #. Keep in mind that this is only a simplistic example, and that the actual code you write depends entirely on your actual project.

Four, PHP 5 in the late binding

In my opinion, late binding is the important reason why Java and C # are so compelling. They allow the base class method to invoke the method with "this" or $this (even if they do not exist in the base class or call a method in a basis class, it may be replaced by another version in the inheriting class). You can assume that the following implementations are allowed in PHP:

Class person{
function Addfeedback ($messageArray) {
$this->parsefeedback ($messageArray);
Write to Database
}
}
Class David extends person{
function Parsefeedback ($messageArray) {
Do some analysis
}
}
? >

Remember, there is no parsefeedback in the person class. Now, assuming you have this part of the implementation code (for the sake of this example), this will cause $myperson to become a David object:

$myPerson = Person::getperson ($name);
$myPerson->addfeedback ($messageArray);
? >

Analysis Error occurred! The approximate error message is that the method Parsefeedback does not exist or some similar information. About the late binding in PHP 5 we'll talk about that! Now let's summarize the concept of late binding.

Late binding means that the method call is bound to the target object at the last minute. This means that when the method is called at run time, those objects already have a specific type. In our example above, you call David::addfeedback (), and since $this in David::addfeedback () references a David object, you can logically assume that parsefeedback () The method exists-but in fact it does not exist because Addfeedback () is defined in person and calls Parsefeedback () from the person class.
Unfortunately, there is no easy way to eliminate this behavior in PHP 5. This means that you may have little to do when you want to create a flexible polymorphic class hierarchy.

I must point out that I chose PHP 5 as the language of this article simply because: this language does not achieve the perfect abstraction of object concept! Because PHP 5 is still in its beta version runtime, this is understandable. In addition, since the language has added abstract classes and interfaces, late binding should also be implemented.

   v. Summary

At this point, you should have a basic understanding of what polymorphism is and why PHP 5 is not perfect in implementing polymorphism. Generally, you should know how to encapsulate conditional behavior with a Polymorphic object model. This, of course, increases the flexibility of your objects and means fewer code implementations. In addition, you improve the clarity of your code by encapsulating behavior that satisfies certain conditions (depending on the state of the object).



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.