There are some posts about this matter, but I didn't clearly get when to use object-oriented coding and when to use programmatic functions in an include. Somebody also mentioned to me that OOP is very heavy to run, and makes more workload. Is this right?
Let's say I have a big file with 50 functions. Why will I want to call these in a class? And not by function_name()? Should I switch and create an object which holds all of my functions? What will be the advantage or specific difference? What benefits does it bring to code OOP in PHP? Modularity?
In a lot of scenarios, procedural programming is just fine. Using OO for the sake of using it is useless, especially if you're just going to end up with POD objects (plain-old-data).
The power of OO comes mainly from inheritance and polymorphism. If you use classes, but never use either of those two concepts, you probably don't need to be using a class in the first place.
One of the nicest places IMO that OO shines in, is allowing you to get rid of switch-on-type code. Consider:
with its OO alternative:
Polymorphism will allow the proper type of "driving" to happen, based on runtime information.
Notes on polymorphism:
The second example here has some premisses: That is that all car classes will either extend an abstract class or implement an interface.
Both allow you to force extending or implementing classes to define a specific function, such as
drive()
. This is very powerful as it allows you todrive()
all cars without having to know which one you're driving; that is because they're extending an abstract class containing thedrive()
method or implementing an interface forcing thedrive()
method to be defined.So as long as you make sure that all your specific cars either extend the abstract class
car
or implement an interface such ascanBeDriven
(both of which must declare thedrive()
method) you can just call thedrive()
method on an object which you know is a car (but not what type of car) without fear of it not being defined, as PHP will throw fatal errors at you until you define those methods in your specific car classes.