Contextual introduction or TL; DR
This response is a democratic and healthy disagreement with the utluiz response. It is necessary to make this clear because some people think that diversity of vision is not constructive or even that it is a fight. I think here we’re doing it healthy and everyone can benefit from it.
Rather than a question that generates a good answer is to have a question that generates several good answers and that make people reflect and learn more, even if they disagree with what is written.
For someone who doesn’t have the patience to read everything or thinks they already know what they need to learn about it, what I say is,:
- OOP is good, but it’s no panacea.
- Everything utluiz says works well in other contexts, but in PHP much of the advantage of OOP is lost.
- OOP brings new problems without solving all of the procedural, so some problems may benefit more from OOP or procedural, OOP is not suitable for anything.
- I say that PHP usually meets problems more suitable for procedural than OOP.
- Much of what is said in the other answer is about static typing, not OO.
- The main disagreement is in using example of bad procedural against good OOP, is unfair!
His answer is not wrong, it has quality, I just want to give another view. In several parts, I agree with what is there. I just think it’s not really contextualized for PHP. PHP’s practice is a little different than what’s described there. The question is about OOP in PHP, not Java.
Some things in this answer make more sense by looking at the original version of his reply.
I strongly recommend watch a video which clearly shows how OOP is more problematic than it looks and where your problem really is. If you want to take the position that OOP is always great, okay, but don’t say I didn’t warn you :)
Best for libraries or complex systems
My opinion has always been (about 30 years) that OOP is best applied to libraries and Apis. Not only, of course, but mostly. And yet not in all library cases. For me OOP shines in problems where PHP does not usually pass close, but at specific points PHP can benefit from the paradigm.
Luckily people often think they are using OOP and are just using a simple class that works as a module or simple structure. The bad part is she got it right by coincidence. Using class does not mean you are doing OOP.
Consuming Apis that were built with OOP is not the same as object-oriented programming.
Abstraction and reuse
I agree that it is common to see people do everything the utluiz says in their response when they procedural program. But I’ve also seen people put everything into classes and make worse mistakes. See (right here on the site) most of the common codes that people write in OOP that make a much bigger mess than the one quoted. She piles up what she can’t and shreds what she can’t, it’s almost random.
Perhaps the explanation is correct if it is purely procedural in the way it was done in the 1960s/70s, but it is not the case to do so. Modularize is an important thing, make everything become an object not so much. I talk a lot about the subject in another question.
C is one of the few languages that do not implement any OOP facility and culture is not trying to force this paradigm into it. People program very well in it without this paradigm in the most complex systems possible and do not have the difficulties and errors cited (neither in the old version, nor in the new version of the utluiz response). The "problem" of language is to be very low level and what is most needed for it is generality and a little more modularization capacity. Okay, there’s also the culture of writing mnemonic code, but this has changed a lot. It remains to be more static than it is. In C and other languages you solve everything that was cited without difficulties.
There’s a specific kind of unquoted reuse in his answer that actually OOP helps, I won’t go into detail not to lengthen.
PHP is a very dynamic language And if you know what you’re doing, you get a lot of reuse without using OOP. In fact you can get even more by taking good advantage of the dynamic features of the language. Reinforcement that I’m not saying that OOP should never be used.
Abstraction is a good thing, and it’s been used since there was a computer, OOP didn’t invent this.
The problem is not the OO or procedural paradigm, or other, is not knowing how to use the tool. And some people sell OOP as if it’s something that you use and everything is solved. Even if it’s not their intention, they end up doing it without realizing it. Many people read that OOP organizes the code and it starts to adopt the paradigm as if it were magic. Who said maybe knows that it is not quite so, who reads and is still learning does not notice the nuances, does not understand that it is not panacea.
Example used
The problem of maintenance cited in this section of his answer occurs in the two paradigms. OOP has even a principle that says you should not modify your classes. Obviously you can not always follow this principle, changes cause difficulties in all paradigms.
The problem cited actually exists because of a language defect, so I quoted C that does not have this defect. PHP doesn’t really have a simple middle-term data structure. Or you have a array dynamic associative that produces the problem he cited or has the class that solves the specific problem. But this is a more static and dynamic thing problem, it is not a dichotomy between procedural and OOP.
Well, use the class then. Why did you put it in a class, are you doing OOP? So C is OO too, she has struct
. Of course I disagree, everyone disagrees.
I will not repeat all the details of what I have already said in numerous answers, some quoted here, OOP is more than creating a class. Putting data into a structure I’ve always found useful, it’s using OOP like this?
enviar_email_cliente($JoseDaSilva); //esta variável é baseada em uma estrutura
You can do better than this, but I didn’t want to change the example that would be bad even in OOP.
There’s nothing oop in there. Whether this variable has a structure defined with AA or with class is not an important detail (internally in PHP it will give in PHP). Choose which one you think is best for your purpose, but the structure maintenance problem is solved. The examples cited create problem by doing it the wrong way.
Do you want the IDE to help? Ok, use the class to create the structure. Only the IDE will help because it has become more static and not because it did OOP.
Did you have the patience to get here? Then you’ll love it this blog that has a good article on this issue. Steve is the guy who can scare most readers away, but at least he doesn’t mess with superficiality, which I know people prefer. I don’t need to tell you that I’m a fan of his, even though I don’t agree with everything he says.
We’re creating a dichotomy between paradigms when actually the question is about typing. PHP would have much more robustness and maintenance facilities for having static typing than for using OOP. And if they take away the dynamic typing it loses its greatest merit. I have repeated several times that if it is to have all this robustness do not use PHP. Forcing the use of static typing and object orientation is misrepresenting what this language has always had good and different from other solutions. Having as an option for some things is very useful.
Call flow of functions
In the original answer there was something about this, see: /revisions/108209/1
I don’t see how the problem cited is solved by OOP. I actually think not only OOP, but all modularization helps to make the problem worse. Also I do not nail making "sausages" to avoid the cited problem, which is real.
It is possible to solve as well as OOP without using it, keeping a clean and organized syntax. If people don’t know how to do it is another problem, but they also don’t know what good is a builder, much used in OOP.
Global variables
Here is also about the original version
A real problem, but OOP doesn’t solve it, there are problems that need the global state.
The global variable has another problem: having global scope.
There are problems that either you complicate the design or does something that ultimately uses global scope, even if disguised. The problem with global scope is when it’s unnecessary and used anyway. There are problems that are inherently global.
In PHP even global abuse causes little problem because they are ephemeral. Of course it can cause some, but it can be a simple solution as well. And I’ll say it one more time, it can cause problems using any tool.
In another context I would find the global ones more dangerous.
I won’t dwell on it further:
Practical example
Based on the original utluiz response
I don’t like this example because it’s comparing a wrong implementation to a right one. Not one paradigm to another. The example shows how not to do procedural and how to do OO, is an unfair comparison.
But it’s not his fault to do this. It’s hard to give good simple examples that the paradigm itself clearly helps.
I understand that in OOP it is harder to make this mistake, but it is easier to make others, and even worse. Note that the difference of being more difficult and easier is derisory.
Example without class and without problems.
$time = Timer();
gerar_relatorio();
Stop($time);
Okay, you didn’t create a class and it all works out.
Has language that would allow to use $time->Stop()
. That is the fault of the language and not of the paradigm. It is only syntax, does not change the semantics, does not change the paradigm.
There’s another example I can do without using a class that would do something similar. The syntax won’t look good in PHP, again it’s a language problem.
I solve this functionally better than procedural or OO, but functional is not fashionable, and is not welcome in PHP. In pseudocode:
Timer(gerar_relatorio, print) //é um exemplo, pode ser de outra forma, print é opcional
Anyway, Timer
is it something from the application or library? This helps to substantiate what I said at the beginning. Nor do I think it is the case of Timer
that can work well without OOP, but OOP is best applied to libraries, general or application-specific.
Use class Timer
ready is programming OO or just consuming something that happened to be made like this?
That one Timer
has to be well written in procedural or OOP, otherwise the comparison is not fair. If it needs to have more data, ok, create a data structure for it, but this is not OOP.
Possibly I would even use OOP to create a timer flexible. But in PHP 99% of the time people are not making libraries, or Erps, or dev tool, or other complex solutions "monolithic". PHP wheel scripts!
Encapsulation
The section cites global variables, but I didn’t see any in the code. I didn’t see a memory leak, I saw a poorly written code. And OOP doesn’t make people magically write code well written.
A person can know how to do good in OOP and bad in procedural. This can happen, there are people who only learned how to do it one way. There is little material teaching to do procedural right, the procedural legacy is really not good.
But what I see most (the reality of some privileged cannot be put to all) is that one does not know how to do both. This site has a good statistical universe to prove this. The procedural is simpler to learn.
Need to encapsulate? Okay, I’m always supportive, even though I’m not always as necessary as you think. Only encapsulate is not OOP, several paradigms preach it.
The mentioned incompatible changes occurred because the code was misspelled. If you misspell OOP the incompatibility will also occur. The answer states that the right thing to do encapsulation will solve a problem. Worth the same for the procedural, doing the correct has no problem at all.
The solution is given by doing it correctly and not because it used OOP or procedural. OOP does not help at this point, unless the person is used to OOP and has no idea how to do the same in procedural, there is an individual cultural issue.
To tell you the truth I thought the new version of the answer even tries to sell, even if it’s unintentional, OOP as a magic solution to all problems. There is a lot of rule to keep doing OOP to make everything work. So apply a lot of rule in Procedural and everything will be fine. It is very common for proponents to justify that OOP is not working because people do not know how to do it. Procedural also.
In a language of script the encapsulation is mainly by the containment of the code in source files that will be loaded on demand and that will be executed and then discarded. Want more granularity? You can, just know how to organize, as you also need to know in OOP.
I know it may be a simplification, but it seems that the answer sells a little the idea that OOP is encapsulating. It may not be intentional, I know. Encapsulation is part of several paradigms, OOP cannot take property for it.
In the process we can also change the internal structure without affecting consumers, just do it right. OOP also only delivers what he promises if he does it right.
I was going to do the procedural version of the new Timer
OOP of the answer, but I found it so confusing that I decided not to risk :) I did not understand what the intention was there. It seems to me that OOP is bad too, but I may be mistaken for not having seen the whole context, it seems that the code mixes responsibilities.
Entities
I find it hardly relevant how the entity is represented. In PHP classes at the bottom are arrays associative, although the implementation differs somewhat from the standard AA of the language. In many situations it is not possible to determine whether everything in the class is being done correctly. The impression I get is that the answer does not consider the reality of PHP. To do everything she preaches PHP would have to have a more static form class than it is, you can’t guarantee what is not static.
Class creation can somewhat bureaucratize development, which is good in most applications made in Java, for example. But PHP is a language with less ceremony. I talk about it a lot in another question.
I admit that very disorganized people may find in OOP some salvation, but she may go wrong by opting for it. I see questions here on the site where the person started doing more procedural and she made mistakes, started doing OOP and got much worse. People are being "forced" to use OOP, no one wants to stay out of this that everyone is using.
Interestingly in OOP hour is preached to join everything, time is preached to separate. Yes, you have to do both, but that’s what I always say, using a general rule for specific cases doesn’t work. So much of what is said about OOP benefit doesn’t mean much when it comes to coding the real problem. It is beautiful in theory and bad in practice. Then who dominates the tool that is complex makes right, who does not dominate gets more confused.
Again, there are cases where there may be gains. The problem is that it is difficult to say without knowing the specific case deeply, thing that would take hours, days, can never be answered here.
Taking the specific example (from the original answer), who guarantees that the validation within the class will be called by itself or externally? Who guarantees that that validation can be used in all situations? Who guarantees that the system can work well with the object always in a unique valid state? I could continue asking several questions. OOP does not guarantee anything more, nor when well done, but the well done in any paradigm can give better guarantees in most situations.
Adding new fields is easier in a more dynamic structure than in a class, although in PHP the class can be streamlined.
All the problems cited can occur in any paradigm and no help do better what was poorly done.
OOP brings new problems, so they blew up the so-called Patterns design famous. Most of them were created to solve OOP problems, which do not exist if using "traditional" PHP. Apply procedural-specific standards and their problems will be solved.
I think if I had a canonical and popular book, maybe called "Design Patters to Procedural" :P and he had come before OOP, the latter would not have all this success. It’s quite a maybe, because the advent of GUI almost forced OOP to exist. And then you enter where OOP should be used, thing away from PHP. OOP makes more sense in JS than PHP.
Be careful not to confuse paradigms with design patterns, nor with typing.
Many of the advantages and disadvantages that people see in OOP (not all, of course) is more tied to language being static than being object-oriented. Interestingly pure OOP (that of Smalltalk) works best in dynamic languages, and does not give all the aforementioned guarantees. The problems cited do not exist in C which is procedural, but is static.
If PHP does not help to ensure much is a fallacy to say that something will be guaranteed if you use the paradigm. Again, the guarantee will come from the correct use of any paradigm, which is very subjective. Or static typing, which is something the class started to introduce in PHP. If it had been called struct
and not class
, would you accept that it is not OOP? I speak of the class as a container data, only, without other gadgets. The gadgets make it OOP.
The new version of the answer has new examples, but it is repetition of what I have already said, I will not comment specifically.
The potential of PHP in different paradigms
I agree with almost everything in this section, I make some reservations or rebounds.
PHP is often used for relatively trivial things. It is a language of script.
Imperative is different from procedural or functional, which are also different from each other. It is not only that one uses procedures and another uses functions, far from it define these paradigms (I will not go into detail, who has doubt, ask specific questions).
Imperative will not really disappear and it is totally orthogonal with several other paradigms, including OOP.
Procedural is also orthogonal, but not so much. The way to organize one or the other is different, at some specific point you choose one or the other, but can mix them in the application as a whole.
I see people actually having a lot of trouble with OOP, in all languages. OOP is not as simple as they sell. It is true that people also have problems with procedural, but it is because they have not learned to develop software in a general way and this, it seems to me, occurs more in PHP than other languages. I see even more in webdev in general, there seems to be greater "skydiving" in this area.
I agree 100% that procedural is easier and how it usually solves without any problem most of the problems that PHP usually works it should be the option default, at least for those who do not have OOP as their fundamental paradigm and who absolutely dominate it, which may even be a case of a golden hammer. Trying to do what you don’t understand is worse than doing it with the "best tool".
Listen to me! Prefer an axe to a chainsaw if you don’t know how to use one. Even if you don’t know how to use the axe either, and you have to cut down the tree anyway. Of course, I’d rather you learn to use both before you do this, but nobody listens to that. A well trained person on the axe will be very quick and will not hurt himself. On the chainsaw he will die before he can get proper training. I say this and people don’t listen. I see it all the time. And people who are well trained tend to encourage the subject to drop the axe and go to the chainsaw thinking that they’re going to magically train themselves, after all they managed to do this and they think that everybody can do the same. Well trained and on the right tree it is possible to benefit from the chainsaw. Although the risk will always be greater and when there is damage will also be. Of course I’m talking about procedural and OOP yet. It seems that loggers are smarter than programmers, they use both.
Lately I have noticed that those who learn OOP first, and even well, have difficulty understanding procedural correctly, maybe even because she has a vision of what OOP is, that, at the very least, I disagree.
Controversy
In the absolutely personal field then don’t take it as absolute truth.
I think many proponents of OOP must have read some book that sold OOP in a marketable way. This form puts OOP in such a generic way that its definition serves for a good part of the paradigms, that is, it talks about organizing code.
If so, then I’ve been programming OOP for over 30 years in everything I do, before I have any language mainstream supporting this "officially" and I have never heard of the term.
But I think OOP is much more than this, and the most of the OOP definitions found place requirements much higher than those cited generically. For me the generic definition of OOP is essentially the same as modularization. Which means she’s trying to "kidnap" something that’s not hers. As well as songs of questionable quality, such as "funk", "Sertanejo", and "pagode" that use names from other original and older musical genres, which had quality, to try to validate themselves.
OOP has no merit of its own?
Within the strictest specification I find OOP well valid for various problems. When it says that OOP is only a way of encapsulating, of putting things together, of separating responsibilities, reusing in general, of abstracting, for me is another paradigm. OOP cannot take what is present in other paradigms, not put anything else and say that it is something different. You can’t say that just putting the noun in front of the verb is an innovation that changes the paradigm. That’s just syntax, you can do this in procedural.
Ah, pure polymorphism does not give the expected robustness. It implemented in a static way it gives.
In questions quoted here I talk in more detail about what I and a lot of people see in OOP.
Do you disagree with that? Okay. I know there are two sides to what OOP is, I accept that. I hope that those who disagree will accept this too and not have their truth as absolute. You have questions on the subject, come on, disagree and substantiate what you think.
Completion
It’s everyone’s right to look for what they think is best for themselves. At no time do I say it’s wrong to use OOP, on the contrary, I use it.
- Do what you dominate and feel more comfortable.
- Start with the simple, and look for solutions to the problems when you realize they arise.
- Don’t solve a problem that doesn’t exist.
- Take it one step at a time.
- Don’t force the use of a needless paradigm.
- Understand what you’re doing, don’t follow recipes.
- Don’t do it 'cause everybody’s doing it.
- Ask yourself if you’re making the right decision. Question more experienced people with specific questions. Take advantage of their experience to accelerate yours, but don’t burn steps.
I think it’s fair that people want to evolve, master new tools, understand everything they can do. What I find strange is when one decides what is good for them without understanding how they use it right, and then ignores other ways that can be better. And give up evolving another way that might be better for her.
The biggest fallacy I see about OOP is that it organizes codes. It helps! How other things help. Who knows what he is doing will do well in any paradigm, who does not know will produce a disaster in any paradigm, but it will be easier to produce disasters in one that he does not dominate.
Today I see that the person does not learn the procedural well because there is no incentive to learn well and does not learn well OOP because it is harder to learn "right".
There is something that makes a difference using a food processor or a blender. There is something that gives in the same.
Why do people consciously prefer to use the knife if the processor is so good? Why use a razor blade if the machine is better? Why use the landline if the mobile solves everything? Why use other paradigms if OOP solves the problem better than them?
Apart from these frameworks complex - and I question quite the use of them in PHP - and some very specific cases, I rarely see valid use for OOP in PHP in the niche where it shines.
So below is an example of how I would apply OOP to a common PHP website:
:)
Related: PHP mixes object-oriented codes and procedural language?
– utluiz