Implementation Scheme of polymorphism in PHP 5.0

Source: Internet
Author: User

Abstract:This article will discuss the concept of polymorphism and Its Application in object-oriented design. It 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 PHP release version. Of course, there are still many problems when using the late binding function. If you are using an earlier version of PHP (PHP 5.0.1 is running on my server), you may find that there is no support for late binding. Therefore, please note that the code in this article may not work in your specific PHP 5 version.

  I. PHP 5 and Polymorphism

This article will discuss the design of polymorphism, one of the most important parts of object-oriented programming. To illustrate the problem, I used PHP 5. Before you continue to read this article, make it clear that this article is not entirely about PHP. Although this language has made great progress in rapid development in the previous two major versions, before it matches more mature languages such as C ++ or Java, its support for objects also goes through a process.

If you are an object-oriented programmer, this article may not be suitable for you, Because polymorphism is a special part of the knowledge: Once you understand it, you will never forget. If you want to learn a little bit about object programming and design, and it is not clear what it means when someone says "an object is a polymorphism", this article is 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.

  2. What is polymorphism?

Polymorphism, defined by dictionary.com, is "in different forms, stages or types appear in an independent organization or in the same type of organization, without any fundamental difference. "From this definition, we can think that polymorphism is a programming method that describes the same object through multiple States or stages. In fact, its true significance lies in: in actual development, we only need to pay attention to the programming of an interface or base class, rather than worrying about the specific class of an object ).

If you are familiar with the design model, you will understand this concept even if you only have a preliminary understanding. In fact, polymorphism may be the greatest tool in pattern-based programming. It allows us to organize similar objects in a logical way so that we don't have to worry about the specific types of objects during specific encoding. Moreover, we only need to program a desired interface or base class. The more abstract an application is, the more flexible it is. polymorphism is one of the best ways to abstract behavior.

For example, let's consider a class called Person. We can use classes called David, Charles, and Alejandro to subclass Person. Person has an abstract method AcceptFeedback (), which must be implemented by all subclasses. This means that any code that uses the subclass of the base class Person can call the AcceptFeedback () method (). You don't have to check whether the object is a David or an Alejandro. You only need to know if it is a Person. The result is that your code only needs to focus on the "minimum public Denominator"-Person class.

In this example, the Person class can also be created as an interface. Of course, there are some differences with the above, mainly because an interface does not give any behavior, but only determines a group of rules. A Person interface requires "you must support the AddFeedback () method", while a Person class can provide some AddFeedback () default method code-you can understand it as "if you do not choose to support AddFeedback (), you should provide a default implementation. "As for how to select an interface or base class, it is not the topic of this Article. However, generally, you need to implement a default method through the base class. If you can briefly outline a set of desired functions to be implemented by your class, you can also use an interface.

  Iii. Application polymorphism Design

We will continue to use the Person base class example. Now let's analyze a non-polymorphism implementation. Different types of Person objects are used in the following example-this is a very bad programming method. Note that the actual Person class is omitted. So far, we only care about code calls.

<? Php
$ 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 'alejandr ':
$ MyPerson-> Feedback-> Append ('awesome Javascript! ');
Break;
Default:
$ MyPerson-> AddFeedback ('yay! ');
}
?>
This example shows the objects with different behaviors, and a switch statement is used to distinguish different Person class objects and execute their corresponding correct operations. Note: feedback comments for different conditions are different here. This may not happen in actual application development; I just want to briefly describe the differences in class implementation.

The following example uses polymorphism.

<? Php
$ Name = $ _ SESSION ['name'];
$ MyPerson = Person: GetPerson ($ name );
$ MyPerson-> AddFeedback ('great Article! ', 'Somerupload', date ('Y-m-d '));
?>
Note that there is no switch statement here, and the most important thing is that there is a lack of objects of the type returned by Person: GetPerson. Another Person: AddFeedback () is a polymorphism method. The behavior is completely encapsulated by a specific class. Remember, whether we are using David, Charles or Alejandro here, it is okay to call the code without having to know the functions of the specific class, but only the basic class.

Although my example is not perfect, it shows the basic usage of polymorphism from the perspective of calling code. Now we need to analyze the internal implementation of these classes. One of the greatest ways to derive from a base class is that the derived class can access the behavior of the parent class, which is often the default implementation, however, it may also appear in the class inheritance chain for creating more complex behaviors. The following is a simple example of this situation.

<? Php
Class Person {
Function AddFeedback ($ comment, $ sender, $ date ){
// Add feedback to the database
}
}
Class David extends Person {
Function AddFeedback ($ comment, $ sender ){
Parent: AddFeedback ($ comment, $ sender,
Date ('Y-m-d '));
}
}
?>
Here, the "Person: AddFeedback" method is called in the AddFeedback method implementation of the David class. You may have noticed that it imitates method overloading in C ++, Java, or C. Remember, this is just a simple example, and the actual code you write depends entirely on your actual project.
4. Late binding in PHP 5

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

<? Php
Class Person {
Function AddFeedback ($ messageArray ){
$ This-> ParseFeedback ($ messageArray );
// Write to database
}
}
Class David extends Person {
Function ParseFeedback ($ messageArray ){
// Perform some analysis
}
}
?>
Remember, there is no ParseFeedback in the Person class. Now, assuming that you have this part of the implementation code (for the sake of explaining the problem in this example), this will cause $ myPerson to become a David object:

<? Php
$ MyPerson = Person: GetPerson ($ name );
$ MyPerson-> AddFeedback ($ messageArray );
?>
An analysis error occurred! The general error message is that the ParseFeedback method does not exist or has similar information. We will discuss the late binding in PHP 5! Next we will summarize the concept of late binding.

Late binding means that the method call is bound to the target object at the last time. This means that when the method is called at runtime, the objects already have a specific type. In the preceding example, you call David: AddFeedback (). Since $ this in David: AddFeedback () references a David object, you can logically assume that the ParseFeedback () method exists -- but in fact it does not exist, because AddFeedback () is defined in Person, and call ParseFeedback () from the Person class ().
Unfortunately, there is no simple way to eliminate such behavior in PHP 5. This means that you may be powerless to create a flexible multi-state class hierarchy.

I must point out that I chose PHP 5 as the expression language of this article only because: This language does not implement the perfect abstraction of object concepts! This is understandable because PHP 5 is still in its beta version. In addition, since abstract classes and interfaces are added to the language, late binding should also be implemented.

  V. Summary

At this point, you should have a basic understanding of what is polymorphism and why PHP 5 is not perfect in achieving polymorphism. Generally, you should know how to encapsulate conditional behavior with a polymorphism object model. Of course, this will increase the flexibility of your object and mean less code implementation. In addition, by encapsulating behaviors that meet certain conditions (depending on the object state), you can improve the Code clarity.

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.