I cannot seem to find a php tutorial about polymorphism so thought that I would.
Polymorphism means that you are deriving from a base class to create a new class, and the polymorphism is when you derive from the base class and implement a interface functions, so that any derived class will have to these functions implement so if you call a function that is defined by the interface to be present, you know it will be implement in some forum.
The basics of creating a interface for the class to implement.
there is no function code, and if you want to implement the interface with your class you use the syntax "implements" on the class definition line e.g.Code:interface Animal {
public function printName();
}
and if you tried to implement the interface Animal without actually implementing the function printName from the Animal interface, you will get a error like.Code:class Cat implements Animal
{...
So the printName method will have to be implement for the PHP code to be "compiled".Code:Fatal error: Class Cat contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (Animal::printName)
Here is fuller code to hopefully explain abit more
and the output would beCode:<?php interface Animal { public function printName(); } class Cat implements Animal { public function printName() { echo "Cat class\n"; } }; class Dog implements Animal { public function printName() { echo "Dog class\n"; } }; $animals = Array( new Cat(), new Dog() ); foreach ($animals as $a) { $a->printName(); } ?>
polymorphism is great, because you will always know if you call a class function that implements a interface you will know that the class will have that function.Code:Cat class Dog class
CodingfriendsCode:int coffeePerDay = 10; // need to cut down!!!
Just asking, I knew of Interfaces but still I haven't used it, even once.
Are there any practical use with Interfaces?
(except software security hardening)
Mnmtanish, I would say that is mainly it.
It is just better programming style really and software development.
Of course things like polymorphism is great for it.
I normally use interfaces ( or pure virtual functions in cpp) purelly because itakes the bigger project easier to follow and also if you are working with a remote company for example, following software development standards means that anyone else can just pick it up and follow on from where I have left off.
CodingfriendsCode:int coffeePerDay = 10; // need to cut down!!!
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks