U ovom ćete članku naučiti kako dijeliti i provoditi kod s polimorfizmom pomoću apstraktnih klasa i sučelja.
Zaronit ćemo dublje u objektno orijentirano programiranje i pokušati razmišljati u smislu Dizajna uzoraka kako bismo dijelili i provodili naš kôd koristeći Polimorfizam.
Sažetak klase
Recimo da imamo klase pod nazivom Čovjek s nekim svojstvima ( name
, age
, height
, fav_drinks
a fav_sports
) i metodama ( giveFirmHandshakes
, beStubborn
i notPutToiletPaper
).
name = $name; $this->age = $age; $this->height = $height; } public function giveFirmHandshakes() { return "I give firm handshakes."; } public function beStubborn() { return "I am stubborn."; } public function notPutToiletPaper() { return "It's not humanly possible to remember to put toilet paper rolls when they are finished"; } }
Moramo navesti ime, dob i visinu da bismo napravili instancu za ovu klasu prema zahtjevu konstruktora.
name, $jack->age, $jack->height); // => Jack - 26 - 5 Feet 6 Inches
Recimo da ovoj klasi želimo dodati novu metodu koja se naziva isActive.
Ova metoda provjerava je li svojstvo aktivno i vraća odgovarajuću poruku ovisno o vrijednosti aktivne, sa zadanom vrijednošću false. Možemo ga postaviti na istinu za one muškarce koji su aktivni.
active == true) { return "I am an active man."; } else { return "I am an idle man."; } } } $jack = new Man('Jack', '26', '5 Feet 6 Inches'); $jack->active = true; echo $jack->isActive(); // => I am an active man. $jake = new Man('Jake', '30', '6 Feet'); echo "\n" . $jake->isActive(); // => I am an idle man.
Što ako muškarac SAMO nije aktivan ili neaktivan?
Što ako postoji skala od 1 do 4 koja mjeri koliko je čovjek aktivan (1 - neaktivan, 2 - slabo aktivan, 3- umjereno aktivan, 4- vrlo aktivan)?
Možemo imati if..elseif..else izjavu poput ove:
active == 1) { return "I am an idle man."; } elseif ($this->active == 2) { return "I am a lightly active man."; } elseif ($this->active == 3) { return "I am a moderately active man."; } else { return "I am a very active man."; } }
Krenimo sada korak dalje.
Što ako čovjekovo aktivno svojstvo nije samo cijeli broj (1, 2, 3, 4, itd.)? Što ako je vrijednost aktivnog „atletska“ ili „lijena“?
Ne bismo li trebali dodati još izjava elseif u potrazi za podudaranjem s tim nizovima?
Apstraktne klase mogu se koristiti za takav scenarij.
Sa apstraktnim klasama u osnovi definirate klasu kao apstraktnu, a metode koje želite primijeniti kao apstraktne, a da zapravo ne stavite bilo koji kod u te metode.
Zatim kreirate podređenu klasu koja proširuje roditeljsku apstraktnu klasu i implementirate apstraktne metode u tu podređenu klasu.
Na taj ćete način prisiliti sve podređene klase da definiraju vlastitu verziju apstraktnih metoda. Pogledajmo kako svoju isActive()
metodu možemo postaviti kao apstraktnu.
1: Definirajte razred kao apstraktni.
2: Create an abstract method for the method you want to enforce inside the abstract class.
3: Create a child class extending the abstract class.
3: Create a child class extending the abstract class.
4: Implement the abstract method inside the child class.
4: Implement the abstract method inside the child class.
5: Instantiate the child class (NOT the abstract class).
5: Instantiate the child class (NOT the abstract class).
isActive(); // => I am a very active athlete.
Complete abstract class definition and implementation code:
name = $name; $this->age = $age; $this->height = $height; } public function giveFirmHandshakes() { return "I give firm handshakes."; } public function beStubborn() { return "I am stubborn."; } public function notPutToiletPaper() { return "It's not humanly possible to remember to put toilet paper rolls when they are finished"; } abstract public function isActive(); } class AthleticMan extends Man { public function isActive() { return "I am a very active athlete."; } } $jack = new AthleticMan('Jack', '26', '5 feet 6 inches'); echo $jack->isActive(); // => I am a very active athlete.
In this code, you will notice that
isActive()
abstract method is defined inside Man
abstract class and it is implemented inside child class AthleticMan
.
Now
Man
class cannot be instantiated directly to create an object.
isActive(); // => Fatal error: Uncaught Error: Cannot instantiate abstract class Man
Also, every child class of the abstract class (
Man
class) needs to implement all the abstract methods. Lack of such implementation will result in a fatal error.
isActive(); // => Fatal error: Class LazyMan contains 1 abstract method // => and must therefore be declared abstract or implement // => the remaining methods (Man::isActive)
By using abstract classes, you can enforce certain methods to be implemented individually by the child classes.
Interface
Interface
There is another Object Oriented Programming concept that is closely related to Abstract Classes called Interface.
The only difference between Abstract Classes and Interfaces is that in Abstract Classes, you can have a mix of defined methods (
giveFirmHandshakes()
, isStubborn()
, etc.) and abstract methods (isActive()
) inside the parent class. But in Interfaces, you can only define (not implement) methods inside the parent class.
Let’s see how we can convert Man abstract class above to an interface.
1: Define the interface with all the methods (use interface instead of class).
1: Define the interface with all the methods (use interface instead of class).
2: Create a class that implements the interface (use implements instead of extends).
2: Create a class that implements the interface (use implements instead of extends).
This class must implement ALL the methods defined inside the interface including the constructor method.
name = $name; $this->age = $age; $this->height = $height; } public function giveFirmHandshakes() { return "I give firm handshakes."; } public function beStubborn() { return "I am stubborn."; } public function notPutToiletPaper() { return "It's not humanly possible to remember to put toilet paper rolls when they are finished"; } public function isActive() { return "I am a very active athlete."; } }
3: Instantiate the implementing class (AthleticMan)
3: Instantiate the implementing class (AthleticMan)
isActive(); // => I am a very active athlete.
With interfaces, you need to keep in mind that:
The methods cannot be implemented inside the interface.
Variables (properties) cannot be defined inside the interface.
All the methods defined inside the interface need to be implemented in the child (implementing) class.
All the necessary variables need to be defined inside the child class.
Man interface enforces its implementing classes to implement all the methods in the interface.
So, what is the use of interfaces?
Can’t we just create a new class AthleticMan and create all the methods instead of implementing the interface?
This is where Design Patterns come into play.
Interfaces are used when there is a base class (
Man
) that wants to enforce you to do things (construct an object, giveFirmHandshakes, beStubborn, notPutToiletPaper and check if you are active) but doesn’t want to tell you exactly how to do it.
You can just go ahead and create implementing classes with implementations as you deem fit.
As long as all the methods are implemented,
Man
interface doesn’t care how.
We have gone over how and when to use abstract classes and interfaces in PHP. Using these OOP concepts to have classes with different functionality sharing the same base “blueprint” (abstract class or interface) is called Polymorphism.