Implementation Plan of polymorphism in PHP5.0

Source: Internet
Author: User
At this point, you should have a basic understanding of what is polymorphism and why PHP5 is not perfect in achieving polymorphism. In general, you should know how to encapsulate conditional actions with a polymorphism object model. Of course, this will improve the mobility of your object and mean less code implementation. In addition, by encapsulating actions that meet certain conditions (depending on the state of the object), you also improve the understanding of the code: this article will discuss the concept of polymorphism and its use in object-oriented design. It will also analyze how to apply polymorphism in PHP 5 and its advantages.

Support for late binding has been implemented in the latest PHP release version. Of course, there are still many titles when applying the late binding function. If you are using an older version of PHP (PHP 5.0.1 is running on my server), you may find that it lacks 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 clarify the title, I applied PHP 5. Before you continue browsing, please first understand that this article is not complete about PHP. Although this language has been greatly improved in rapid development in the previous two important versions, before it matches more mature languages such as C or Java, it also goes through a process to support objects.

If you are an object-oriented programmer, this article may not be suitable for you, because of the special knowledge of polymorphism: once you understand it, you will never forget it. If you want to know a little bit about object programming and design, and don't quite understand what it means when someone says, 'an object is polymorphism, 'then this article is suitable 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 strengths and weaknesses of object programming in PHP 5.

2. what is polymorphism?

Polymorphism, which comes from dictionary.com, is defined as 'present in different situations, stages or types in an independent organization or in the same type of organization, and there is no basic difference. 'From this definition, we can think that polymorphism is a programming method that describes similar objects through multiple states or stages. Actually, it really means that in actual development, we only need to focus on the programming of an interface or base class, instead of worrying about the specific class of an object ).

If you are familiar with the design model, even if you have a preliminary understanding, you will also understand this concept. In fact, polymorphism may be the greatest tool in pattern-based programming. It promises that we can 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 an interface or a base class in the current period. The more abstract a Exploitation program is, the more mobile it appears-and polymorphism is one of the best ways to abstract actions.

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 the method AcceptFeedback () can be called by the code of any subclass of the application base class Person (). 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 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, the important thing is: an interface does not give any action, but only determines a group of rules. A Person interface requests the 'you must support AddFeedback () method', while a Person class can provide some AddFeedback () default Code of the method-you can understand it as 'if you do not choose to support AddFeedback (), you should provide a default implementation. 'The selection of interfaces or base classes is not the topic of this article. However, in general, you need to use base classes to implement a default method. If you can briefly outline the effect of a set of phases of your class, you can also apply an interface.

III. design with polymorphism

We will continue to apply the example of the Person base class. now let's analyze the implementation of a non-polymorphism. Different types of Person objects are applied in the following example-this is an unimagined programming method. Note that the actual Person class is omitted. So far, we only care about the title of the code call.

<? 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 actions, and a switch statement is used to differentiate different Person class objects, so as to implement their corresponding precise control. Note that feedback comments for different conditions are different here. This situation may not be displayed in actual application development; I just want to briefly clarify the differences in class implementation.

The following example applies 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 object types related to Person: GetPerson. Another Person: AddFeedback () is a polymorphism method. Complete actions are encapsulated by specific classes. Remember that no matter whether we use David, Charles or Alejandro here, the calling code never has to understand the functions of a specific class, but only knows the base class.

Although my example is not complete, 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 action of the parent class, which is often implemented by default, however, it may also be presented in the class continuity chain for creating more complex actions. The following is a brief demonstration 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 be aware that it imitates method overloading in C, Java, or C. Remember, this is only a simple example, and the actual code you write is fully dependent 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 eye-catching. They promise that the base class methods use 'eas' or $ this to call the method (even if they do not exist in the base class or call a method in the base class, it may be replaced by another version in the continuous class ). You can think of the following implementation as promised 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 clarifying the title 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, let's get back to 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 get rid of such actions in PHP 5. This means that you may be powerless when you want to create a mobile multi-state hierarchy.

I must point out that I chose PHP 5 as the expression language in this article because it does not implement a complete abstraction of the object concept! PHP 5 is still in its beta version, so this is understandable. In addition, since the language includes abstract classes and interfaces, late binding should also be implemented.

V. Summary

At this point, you should understand what polymorphism is and why PHP 5 is not complete in implementing polymorphism. In general, you should know how to encapsulate conditional actions with a polymorphism object model. Of course, this will improve the mobility of your object and mean less code implementation. In addition, by encapsulating actions that meet certain conditions (depending on the state of the object), you also improve the understanding of the code.


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.