Analysis of the implementation scheme of polymorphism in PHP 5.0

Source: Internet
Author: User
Keywords Analysis of the implementation scheme of polymorphism in PHP 5.0

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 the advantages and disadvantages of the existing.

Support for late binding has been implemented in the latest releases of PHP. Of course, there are many problems when using its late binding feature. If you are using an older version of PHP (my server is running PHP 5.0.1), then 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 version of PHP 5.

One, PHP 5 and polymorphism

This article wants to 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 reading, make sure that this article is not entirely about PHP. Although this language has made great strides in rapid development in the previous two major releases, it has a history of support for objects before it rivals more mature languages such as C + + or java.

If you are an introduction to object-oriented programming, 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 it. This article is right for you if you want to learn a little bit about object programming and design knowledge, and when someone says "something is polymorphic" and is not quite sure what it means.
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, is "in different forms, stages or types that appear in an independent organization or in the same organization, without the fundamental difference." "By this definition, we can think of polymorphism as a way of describing the same object through a variety of states or stages." In fact, the real meaning of it is: in real development, we only need to focus on the programming of an interface or a base class, without worrying about the specific class that an object belongs to.

If you are familiar with design patterns, even if there is a preliminary understanding, then you will understand this concept. 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 exact type of the object in the specific encoding, and we only need to program a desired interface or base class. 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 call Method Acceptfeedback (). You don't have to check whether the object is a David or a Alejandro, just know that it is a person 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: one interface does not give any behavior, and only a set of rules is determined. A person interface requires "You must support the Addfeedback () method", and a person class can provide some default code for the Addfeedback () method-you can understand it as "if you don't choose to support Addfeedback (), Then you should provide a default implementation. "It is not the subject of this article as to how to choose an interface or base class, but in general you need to implement a default method through a base class." You can also use an interface if you can simply sketch out a set of desired functions that your class will implement.

Third, the application of polymorphism design

We will continue to use the example of the person base class, and now let us analyze a non-polymorphic implementation. Different types of person objects are used in the following examples--a very undesirable way to programmatically do this. Note that the actual person class is omitted. So far, we are only concerned with the issue of code invocation.

$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 correct actions. Note that the feedback annotations for different conditions here are different. This may not be the case in real-world application development; I'm simply explaining 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 is no switch statement, and most importantly, the lack of what type of Object The Person::getperson () will return. The other Person::addfeedback () is a polymorphic method. Behavior is completely encapsulated 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, from the point of view of calling code, it has shown the basic usage of polymorphism. Now we need to analyze the internal implementations of these classes. One of the great things to 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 it can also be used to create more complex behaviors in the class inheritance chain. Here is a simple demonstration of this situation.

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 '));
}
}
? >

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

Iv. late binding in PHP 5

In my opinion, late binding is an important reason to make Java and C # so compelling. They allow the base class method to invoke methods with "This" or $this (even if they do not exist in the base class or call a method in a basic class, it may be substituted for 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) {
Perform some analysis
}
}
? >

Remember that 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);
? >

A parsing error has occurred! The approximate error message is that the method Parsefeedback does not exist or some similar information. About late Binding in PHP 5 we'll talk about this! 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 the parsefeedback () The method is present-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 might be powerless when you want to create a flexible polymorphic class hierarchy.

I must point out that I chose PHP 5 as the expression language of this article only because: this language does not achieve the perfect abstraction of object concept! This is possible because PHP 5 is still in its beta version run. In addition, since the language is joined with 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 for 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 behaviors that meet 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.