I’m trying to learn how to best use OOP in PHP. Please be aware that even if I studied the theory of this new “world” I didn’t enter the OOP thinking yet obviously.
What’s the difference between using normal, separated functions and putting them in a class as methods?
Let’s say I have a class called “shop”.
It has these methods: retrieveitems, deleteitems, updateitems, additems
Except for the fact that I can call methods inside methods with a simple “$this”, what is the difference between putting them in different functions without a class? I mean, for example, I still can call function deleteitems inside function retrieveitems right? Even if not in a class?
Please help me understand what I’m missing.
OOP provides, among other things, encapsulation.
Now you can create instances:
And each one of them is independent from each other. If I do
$computerShop->removeItem('water'),$hardwareStoreshould still havewaterin theirinventory. (see it in action) Doing this the procedural way is much messier.Another cool thing about OOP is that you can use inheritance and polymorphism:
Now both
CatandDogs can call the methodeat()even though they are not explicitly declared in their classes – it’s been inherited from their parent classAnimal. They also have aspeak()method that does different things. Pretty neat, huh?Wikipedia:
Object-oriented programming, Encapsulation, Inheritance, Polymorphism