Читать книгу PHP This! A Beginners Guide to Learning Object Oriented PHP - Michelle Gosney - Страница 14

Polymorphism

Оглавление

Now that you know that a class is a blueprint and that an object is constructed based on that class it is important to understand that many different objects can be created from the same class. I may have a single class for a table but I can create many different kinds of table objects from that class. I could have a round table, a square table, a long table a short table. I could have a blue table or a brown table. I could have a table made of oak or one made from plastic; all from the same base class.

Polymorphism simply means many forms. In computer programming, polymorphism is the ability to create a variable, a function, or an object that has more than one form in order to provide capability of adapting to what needs to be done. It is a mechanism by which objects of different types can process data through a single interface. Polymorphism is used to make applications more modular and extensible. Instead of messy, hard to read conditional statements describing different courses of action, you create interchangeable objects that you select based on what you need. That is the fundamental goal of polymorphism.

Polymorphism is a mechanism by which objects of different types can process data through a single interface.

Using a typical illustrative example, a program might define a type of object called Animal, containing a function called speak() and, through inheritance, derive object sub-types such as Cow, Dog, etc. that each have their own specific implementation of the speak() function. The mechanism of polymorphism allows such a program to call the speak() function without actually knowing whether it is calling it for a Cow, Dog, or any other derivative Animal, while executing the correct function for the specific type of Animal.

Polymorphism is not the same as method overloading or method overriding (in OOP, a method is a function that belongs to a class, while the class variables are referred to as its members) and should not be confused with these.

PHP This! A Beginners Guide to Learning Object Oriented  PHP

Подняться наверх