How important are classes? (PHP) [closed] - php

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
I dont know much about classes, but have a reasonable knowledge of PHP/MySQL.
But why should I learn classes? I know they are important but what benefits can I see using them that I cant with?

Encapsulation, for one.
Steve Jobs once used a good analogy (it was in an interview). To paraphrase from memory, he said
If I want my clothes cleaned, and give
them to a friend, he will return them
cleaned. I do not care if he had to
get a cab, got a bite to eat or
whatever, I just want to give him my
clothes and have them returned clean.
Also, I found the interview. Interesting read.
Basically, he is saying that he doesn't care about the implementation details. That's what OO can do. Hide all the stuff inside a class through visibility and so forth. If you want a list of files from a folder, you could do
$files = new FilesInFolder('your/path');
$files->getByExtension('*.jpg');
You don't care if it uses glob() or readdir().
Update
As opposed to a file full of global functions such as functions.php: you can group all of the functions to specific tools. For example in the example above, you could have getFiles() and filterFilesByExtension() but these 2 related functions will be in the global scope, not to mention the second one will require you pass the files as an array back to it.

Actually, I've found that it is often simpler to use function-based programming in php than object oriented. There are a lot of ways in which just using function libraries and trying to keep your code simple and direct make your php scripts more maintainable, especially if you minimize state to increase reproducibility.
Objects & classes are one tool that you should get to know so that you can choose between the different options, but certainly not the only choice, now that php 5.3 has first class functions, moving more in the direction of true functional programming is another tool that you could get to know.
Php's background is very function-based, a huge portion of the native language provided is functions and sometimes the square peg of objects doesn't fit in php's round hole.
This certainly wouldn't apply to Java, but php's background is very rooted in functions.
Edit:
Let's be clear, to be effective at php you will have to have a good grasp of objects, because you are going to encounter it frequently, and if you work for other people in php, you'll probably have to write OO yourself on your employer's behalf. So get to know it well. But don't stop at OO and consider it the be-all-end-all solution. In fact, when it comes to dealing with other people's bad php code, I have found solid function-based programming to often be a simpler tool for refactoring and cleaning up bad code.
I would say there are a few ways to write php code:
Bad procedural code (little reusability, probably uses functions, but not well, probably uses objects, but not well).
Good function-based code (maximized reusability, minimized complexities of state, separation of concerns)
Bad object oriented code (large multifaceted objects, complex hierarchies, etc)
Good object oriented code (specific-task objects, clear separation of concerns like MVC)
And eventually, as php 5.3 matures, we'll be able to start throwing in a bit more functional programming into the "good function-based code" category and it will become an even more effective alternative. In the meantime, though, get comfortable with 2 and 4 because you'll need 'em both.

Classes are important when dealing with code reuse, they also provide well organized and cleaner code, in my opinion.
Depending on specific applications/projects you are working on, classes can make sense.
Update:
Also, it might be worth glancing at, and noting that Wikipedia has a section in Class (computer science) called Reasons for using classes which demonstrate a few key points for using classes.
Also, from your previous questions it seems you do a lot of work with PHP and MySQL. To demonstrate how beneficial classes are, you could create a Connection class that handles connecting to your MySQL database, so any changes made to the database you can edit in one single place, (your Connection class) rather than finding all the lines of code when it's called.

One of the main points of object oriented programming (objects and classes) is to make your programs more modular; when you work on one part, you don't have to work on the details of another part of the program. Depending on what kind of code you are writing, this may or may not be important.
A lot of people on a page like this will claim that a) OOP is the only good way to write programs and b) it is desperately needed for any program and/or home-page. I think if you think of what you are writing as a home-page, you probably do not need OOP, unless it's a very large home-page.
OOP is by far the most common programming paradigm, which makes it important to learn, if you want to be a programmer. However, most PHP is not written in an object oriented style and some of it is ok anyway (even though a lot of it is not).
If you think that the PHP that you are writing is hard to manage, learning OOP is probably a good idea, even if you only get the practice. You might even want to try it out in another language like, say, Java or Ruby. It is probably easier to find good books about OOP in those languages.

Classes and objects in PHP make one very important aspect of programming much much easier: abstraction.
Like many languages that have objects in addition to scalar types, objects in PHP simple take the aggregated item concept one step further. Things like arrays/lists let you work with a collection of data as one item. Objects make that just a little easier and also let you have code specific to that collection to manipulate that collection.
How about an example? I was involved in an educational intranet application some years ago. Its prime goal was to track academic progress over time and to do that it has to know about student enrolments, class membership and thus timetables. We needed a data point for a particular scheduled class in time. Initially, it was a list of data parameters passed into functions. Year, term, week, day, period. Then it needed to be returned, as well. Now it was an array. Then we needed specialised functions for manipulating it, mainly turning it into a real time and back again. So I made it an object.
Now, as an object, the conversion routines were thoroughly abstracted away. You could ask the object to convert itself and without the calling code caring or knowing, the object could cache expensive calculations. Code to handle tricky things like daylight savings was written and debugged once. The object just made it so much easier to handle the data.
Much of the PHP code was still function oriented. The startup logic on each page called a dozen functions to get everything going. But there were objects, too, for when the data needed it. And it made a lot of the code a lot simpler and more robust.

As always depends what you have to do, the Object Oriented way can become useful for many reasons:
If well designed increase the order inside your projects that means much more code re-usability, reduce the written code, less time spent in troubleshooting.
Collaboration if you have to work with many other peoples it's much more simple to maintain the code
Modularity it will give you a very good project organization
Encapsulation By implementing classes you can hide the code complexity inside the objects and keep "only" the logic part in the main code.

Related

Begin with OOP by using classes as a collection of methods? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
Is it wise to start with object-oriented PHP by using classes as a collection of methods? Are there any drawbacks with this approach?
I know OOP is much more than this, but my PHP-projects are too small to take advantage of all that OOP has to offer. On the other hand, my projects are becoming too big to update/maintain just with procedural programming.
I have read many topics about OOP and once in a while somebody says "OOP is more than just a collection of functions" (or something along these lines). It made me think: that may be true, but it also may be my chance to finally dive into the world of OO-programming by doing just that.
So, is this a smart first step to actually start using and learning OOP? Or are there serious drawbacks I need to know about?
Your question is real broad, however it deserves a simple answer you can memorize and keep with you while you continue your journey into the world of object oriented analysis and design (OOAD).
So, is this a smart first step to actually start using and learning OOP? Or are there serious drawbacks I need to know about?
As you can imagine, it is not possible that we answer this question directly. What is smart and what not depends a lot of our own abilities. E.g. for some persons it might be smart, because it helps them to stop errors early and this is the way to go. For others, it might be the complete desaster, because they don't spot any error, continue developing a software because they think: If I don't spot an error, this is totally right.
So how to resolve this dilemma? Easy, we have two parts in OOP you can easily learn about and keep with you. The first is called S.T.U.P.I.D. - you might imagine what it means if something falls into this category, and the second is called S.O.L.I.D. and it's likewise self-speaking how to treat the somethings in there.
So don't be STUPID, grasp SOLID.
Disclaimer: I haven't dealt with php in a while, so my syntax might be wrong.
The term OOP is a bit fuzzy imo, meaning that different people will think of slightly different things when they hear it, so don't be confused when you hear contradictory things about it.
Structuring similar functions together using classes won't hurt your code, but then you basically just use classes as namespaces for your functions. Usually, you will want to define classes in a way that encapsulates some aspect of your system, meaning that only the code of that class will ever have to deal with that aspect directly, and everyone else just uses that class.
For example, you could have a class that manages a print job queue. If you have some code that wants to print a document, it doesn't have to know how or where the jobs are queued or how they are sent to the printer, it only needs to know a print job queue object (let's call it $jobQueue), which might have a method like $jobQueue->enqueue($document).
Now you might argue: "That code could just as well use a global function enqueueJob($document)," and that is true until you want to have more than one queue (for different printers), and queues that work in different ways (store jobs in a database, in memory, or not at all - imagine a queue that goes right to the recycling bin :)). With OOP, this kind of scenario is no problem, and these details stay completely hidden from the code that wants to print a document - all it has to care about is that it has a job queue object with an enqueue method.
To get this kind of "interchangeability" of job queues they need to have a common interface (in this case, the enqueue method,) which has to be carefully chosen to cover all the needs of the code that wants to print things, but without making too many assumptions about how a print queue works. For example, you could imagine that the enqueue method takes a file path as argument which tells the queue where to store its files - but that interface would be useless for a queue that works on a database. This is the art of finding good abstractions.
Now to come back to your original question, just packing related functions together into a class is not really OOP in my opinion, as long as there is no thought about which abstractions / interfaces the new class is supposed to provide. Without that, all code that uses this new class will be hardwired to use it, and will need to be changed / reexamined if you ever decide that you DO need a different kind of printer queue. :)
However, "not OOP" is not the same as "not a good idea". I say go for it and rearrange your functions. In my opinion, it is important to keep in mind that not everything needs to be an object or fit some abstraction. But maybe you will find out that you do have some functions which do similar things (queue in file, queue in database) which could be abstracted to a common interface.
OOP is basicly just set of methods. But thinking in programming is different. In classes, you encapsulate similar funcionality. Code is more readable, you dont need to write same functionality over and over again. It is also more secure (private members), if you are writing library, end-user can change only what you want etc.
So I wouln´t recomment to try bypass OOP with set of functions and use real OOP instead. There is no reason why not.
I don't recommend, you will get used to write procedural code masked as OOP, which is not really what you want. Could be hard at first, but learn OOP with all it's features, read about patterns, emphasise on coding standards and, most important, study applications with object-oriented architecture.
Some things are functional, procedural and based on an object. Use the one that is the most appropriate for the circumstance. You will not got far wrong with that philosophy.
As this question isn't really related to php but to OOP in general, this answer should be valid for many languages.
There exists different pattern in OOP. I suggest reading about the "gang of four". It's a really nice book that explains some of the most basic pattern that can be used when doing OOP.
Instead of using a class to keep a sets of static function, you should consider storing all of your functions in a namespace.
Classes often define objects (like physical object). Any physical object has a sets of properties and behaviors.
When designing a class, you're trying to define those behaviors and properties. For example, a bag.
class Bag:
// Methods
function open: ...
function close: ...
function empty: ...
function add(item): ...
// Properties
array items: []
bool is_open: false
Some properties or method can be hidden or visible to the world. In my example, you could make the function add throw an exception whenever you try to empty or add an object to a closed bag. It's clear that all of the methods here are related to the actual object.
Adding methods or attribute that are unrelated to the bag should belong in a different namespace or class. It really depends on what you're trying to do.

Why should I start writing object-oriented code in PHP?

I have been using regular PHP for some time now. My formal code training is zero. Whatever I've learned I've found here, on the PHP documentation site, the MySQL documentation, etc.
I write PHP from scratch. I use functions for tasks that re-occur, I apply MVC to write more maintainable code, and I recently wrote a nice little library with some of my functions so I can save time in future projects. Long story short, without being some sort of guru, I have a decent relationship with PHP, and so far it seems to get things done for me.
So my questions are the following: Why should I start writing object-oriented code in PHP? How will it make my programming life better and why is it better than the traditional way of doing things?
OOP was made to make programming languages more similar to real life.
What does that mean?
We live in a world of objects. You are an object (Person), you live in an object House, that House object (as well as any other House object) has an House::$address and House::$number, your house probably contains other objects such as LivingRoom and Kitchen. The Kitchen can hold Oven and Stove and Refrigerator, which are all extensions of the KitchenAppliance object.
OOP programming takes that approach, and incorporates it into the programming world.
How does it help me?
Well, there are several things:
It makes your code more maintainable. Instead of dividing your program into tasks (functions), you divide it into objects, if you think of a database connection as an object (meaning, there can be multiple database connections, they share methods and properties, but each is preformed on a different instance), it makes it easier to understand and maintain.
It makes your code more readable. You define an object with the class decleration, and then call it with the new ClassName() keyword.
It allows for extensibility and flexibility. Just like KitchenAppliance can be extended into Oven or Stove, so can your objects and classes.
Summary
OOP programming comes with many advantages. It requires a slightly different way of thinking, but eventually, it's worth it.
You have received a lot of comprehensive answers, so I will use one argument: design patterns. (http://en.wikipedia.org/wiki/Software_design_pattern).
You can find tones of solutions for commons problem, which can save your time and improve quality of your code.
Some design patterns examples:
Strategy pattern (http://en.wikipedia.org/wiki/Strategy_pattern) - for using different alghoritms/solutions in class without changing it
Observer pattern (http://en.wikipedia.org/wiki/Observer_pattern) - you can invoke different actions (and register them during execution) - when state of object changes.
Decorator pattern (http://en.wikipedia.org/wiki/Decorator_pattern) - you can extend your object dynamically, and use new objects in same manner as old.
Franky speaking, if you want to better understand OOP, you have to:
Learn or understand common design pattern.
Start using unit testing, you will find out that lack of dependency injection can be real pain in bad architecture.
learn and understand OOP principles, like SOLID http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29.
Without this you will be using functions encapsulated in classess, like in namespace, not OOP.
For sure you can write your code without OOP and try to implement designs/patterns like MVC without using just a single object.
I don't want to answer why to program in OOP. This you could read in e.g. on this Stack Overflow question.
I think you want to know, when and why you would fail with your coding behavior:
This would be at the moment when you try to work with another person together. The other programmer would never find your code readable. He will take a long time till he understands how your software works.
I think it's hard to separate tasks in your code for teamwork. How are your files separated, and how is the naming convention? You have to solve this by your own and don't reuse every known pattern.
What are you doing with third-party stuff? How do you integrate them? I do not know any usable library without using an OOP schema...
There are many more problems which are surely possible to solve, but every time you lose the possibility for others to understand your code and to reuse it in other programs...
One word: cohesion.
When you start developing software using objects (especially when those objects use Dependency Injection), you find that common functionality starts to gravitate into their own specialised classes that are reused. This makes maintaining and enhancing the software MUCH easier, and results in higher quality software.
Example:
Many applications use sessions, for storing all sorts of stuff. When all session data is managed by a specialised session manager class, all the code that is responsible for dealing with the session is kept in one place. If you want to change the way you application uses session data (perhaps to make it more secure, or more efficient), you only need to change code in one place.
I made the jump to OOP PHP three months ago and it is one of the best things I have done.
I started off with PHP Object-Orientated Solutions and have just finished Real-world Solutions for Developing High-quality PHP Frameworks and Applications. Both of those books have helped me a lot, and I highly recommend them.
The learning curve is quite high. But I guarantee, you will be glad you've turned to OOP.
With OO you can develop applications a lot faster and in a cleaner way. You could easy to reuse your extisting classes with extending them (reducing your code base).
With OO design you only have to deal with small pieces of codes at any one time, not a bunch a functions in a file with 3000+ lines of code. You should also look after the
SOLID guidelines.

How do i get out of the habit of procedural programming and into object oriented programming?

I'm hoping to get some tips to kinda help me break out of what i consider after all these years a bad habit of procedural programming. Every time i attempt to do a project in OOP i end up eventually reverting to procedural. I guess i'm not completely convinced with OOP (even though i think i've heard everything good about it!).
So i guess any good practical examples of common programming tasks that i often carry out such as user authentication/management, data parsing, CMS/Blogging/eComs are the kinda of things i do often, yet i haven't been able to get my head around how to do them in OOP and away from procedural, especially as the systems i build tend to work and work well.
One thing i can see as a downfall to my development, is that i do reuse my code often, and it often needs more rewrites and improvement, but i sometimes consider this as a natural evolution of my software development.
Yet i want to change! to my fellow programmers, help :) any tips on how i can break out of this nasty habbit?
What is the point in using object-oriented programming when you cannot find good reasons or motivation to do so?
You must be motivated by the need to conceive and manipulate ideas as objects. There are people who feel the need to be perceptive of concepts, flow or functions rather than objects and they are then motivated towards programming oriented towards concepts, ideas, or functional flow.
Some 13 years ago, I switched to c++ from c simply because there were ideas I needed but c would not easily perform. In short, my need motivated my programming oriented towards objects.
The object-oriented mind-set
First, you have bytes, chars, integers and floats.
Then your programme starts being cluttered with all kinds of variables, local and static.
Then you decide to group them into structs because you figured that all the variables which are commonly passed around.
Conglomeration of data
So like printer's info should have all its variables enclosed into the Printer struct:
{id, name, location,
impactType(laser|inkjet|ribbon),
manufacturer, networkAddr},
etc.
So that now, when you call function after function over printer info, you don't have functions with a long list of arguments or a large collection of static variables with huge possibilities of cross-talk.
Incorporation of information
But data conglomeration is not good enough. I still have to depend on a bunch of functions to process the data. Therefore, I had a smart idea or incorporating function pointers into the Printer struct.
{id, name, location,
impactType(laser|inkjet|ribbon),
manufacturer, networkAddr,
*print(struct printer),
*clean(struct printer)
}
Data graduates into information when data contains the processes on how to treat/perceive the data.
Quantization of information
Now laser, ribbon and inkjet printers do not all have the same set of information but they all have a most common set of denominators (LCD) in information:
Info common to any printer: id, name, location, etc
Info found only in ribbon printers: usedCycles, ribbon(fabric|cellophane), colourBands, etc
Info found only in inkjet: ink cartridges, etc
Info found only in lasers: ...
For me and many object-oriented cohorts, we prefer to quantize all the common info into one common information encapsulation, rather than define a separate struct/encapsulation for each printer type.
Then, we prefer to use a framework which would manage all the function referencing for each type of printer because not all printers print or are cleaned the same way.
So your preference/motivation oriented away from objects is telling you that your programming life is easier if you do not use objects? That you prefer to manage all those structural complexities yourself. You must not have written enough software to feel that way.
The necessity of laziness
Some people say - necessity is the mother of creativity. (as well as, Love of money is the root of evil).
But to me and my cohorts - laziness in the face of necessity are the parents of creativity. (as well as the lack of money is the other parent of evil).
Therefore, I urge you to adopt a lazy attitude towards programming so that the principle of the shortest path would kick into your life and you'll find but have no other choice than to graduate towards orienting yourself towards programming with objects.
Step 1. Read a good Design Patterns book. http://www.oodesign.com/
Step 2. Pick something you already know and rework it from an OO perspective. This is the Code Dojo approach. Take a problem that you already understand, and define the object classes.
I did this -- and wrote down what I did.
See http://homepage.mac.com/s_lott/books/oodesign.html#book-oodesign
You can do the same series of exercises to get the hang of OO design and code.
The OO mindset is based on principles that lie at a much more basic level than design patterns. Design patterns are somehow fashionable these days (and have been for a while), and they are useful, but they are just one more layer that you can put upon more basic stuff that you absolutely must learn and master if you want to do OO properly. In other words: you can do OO perfectly without design patterns. In fact, many of us did OO well before the phrase "design patterns" was even coined.
Now, there is stuff you can't do without. I suggest you start at the basics. Read and understand "Object-Oriented Software Construction" 2nd edition by Bertrand Meyer. It's probably the best book on OO programming around, both in width and depth. That is if you're interested in programming.
First, congrats on taking steps to learn something new! I hate it when developers decide to NOT evolve with technology.
As far as moving from procedural programming to OOP, I would say that one thing that you can do is take an existing app (as others have mentioned) and, before you even open a text editor, sit down and think about how each aspect of the application would be converted. I have found that more than half of OO programming is defining the conceptual objects in your mind first.
Again, I will agree with everyone's recommendations on design patterns. Specifically, I would look into the MVC (Model-View-Controller) pattern as this one might be the easiest one to grasp. You have already written code, so you should be able to look at your existing applications and begin putting each part into the M,V or C categories.
Best of luck and have fun!
There are already quite a few answers about where to find information on programming in an object-oriented fashion. Indeed, there are many great books out there that will define the basic concepts however I think the question was more on how to "stick with it" through development for someone new to the method.
Of the many concepts in object-oriented programming, the main one that will keep you on track as a newcomer is encapsulation. Does my class know how to take care of itself? Does my class have behaviour? If it doesn't, then you don't have a class, you have a structure and you'll likely be writing a lot of procedures to change its state (as it's said, "you are back to writing C in Java"). Does my class only expose methods publicly that are required for its use? Those questions may not be terribly elaborated upon but perhaps consider this thought experiment when designing your classes: What if each one of your application's classes were to be developed and maintained by a different developer on the internet and the classes also had to interact with eachother over the internet. Would each developer agree that the class they are writing and maintaining adheres to the single responsibility principle and therefore be happy that they aren't maintaining what should be someone elses code?
Regarding the design of class interfaces, consider writing all of the code that uses your classes first. Don't worry about what has to happen at the metal yet. You should be able to stub out the entire program in terms of the class relationships before you write your first bit-twiddling implementation detail. If you can't do this without twiddling bits or making a variable public, then it is time to go back to your class relationship diagram and see if you are missing an abstraction. Phrased another way, use your code before you write your code. Do this first, and you might be suprised how clean your code and interfaces turn out if you've never done it before.
While design patterns are certainly good to learn, and some are extremely powerful, they aren't generally intrinsically object-oriented and as some argue (and I tend to agree) design patterns are often just exposed weaknesses in the language. One language's design patterns is another's basic founding principles. So when starting, don't get hung up on whether or not some relationship is a good candidate for a bridge or a facade; this is not specific to object-oriented thought, this is related to what a specific language's constructs afford.
Don't.
First, learn writing. Second, learn user experience and interaction design. Third, learn business analysis. Fourth, learn role modeling.
Now that you know what objects are, you will come to see that objects are not found in code. They are found at runtime; in the space between the machine and the user's mind. This is what object orientation really means. Unfortunately recent academia has twisted it into an engineering concept. Nothing could be further off the mark. And try as they might to emulate, the end result is crap. Why? Because the "OOP" paradigm as the industry knows it today is built on a fundamentally flawed idea: decompositional analysis of identity. How is this flawed? Because identity in and of itself is meaningless. It is void. In a mathematical sense, in a philosophical sense. This is not how a human being perceives and interacts with the world.
Canon: Alan Kay, Trygve Reenskaug, James (Jim) Coplien
How I wish I was in your position. :)
I think it helps to first skim over some existing, decent, proven object-oriented code (e.g. Qt source code) so you can get a feel for "how it's done". After that, learning from a book or creating your own framework will be much more effective.
In general, it really helps to see things in context before reading about and practicing them, as it gives you moments to say to yourself, "Oh, that's why they did that!" At least that's how it works for me.
The hard part of OO is which stuff should be put together into one object. As you already mentioned the evolution of your source code, here you have a simple guideline on how to evolve your source code towards an OO design:
"Put stuff together that changes together."
When two pieces of code have similar change velocities, that's a hint that they should be placed in the same object. When the change velocities are different, consider placing them in different objects.
This is also known as "Change Velocity".
If you follow that guideline your code will naturally evolve towards a good OO design. Why?
Fragments of code often have similar
change velocities if they access a
common representation. Every time the
representation changes, all the pieces
of code that use it must change at
once. This is part of the reason we
use objects as modules to encapsulate
representation. Separating interface
from implementation makes sense under
this guideline too - the
implementation changing more often and
thus having a higher change velocity.
If a class has a stable part and an
unstable part, that's a difference in
change velocity that suggests moving
the stable part to a (possibly
abstract) base class.
Similarly, if a class has two parts
which change equally often but at
different times or in different
directions (that is to say, for
different reasons), then that again
suggests refactoring the class.
Sometimes replace "class" with
"method". For example, if one line of
a method is likely to change more
often than the rest - perhaps it is
the line which creates a new object
instance and contains the name of its
class - consider moving it to its own
routine. Then subclasses can easily
effect their change by overriding it.
I came across this concept on C2 wiki many years ago, but I've rarely seen it used since. I find it very useful. It expresses some crucial underlying motivation of object oriented design. Of course, it's therefore blindingly obvious.
These are changes of the program.
There is another sense of change
velocity - you don't want instance
variables changing at different rate,
or rather that is a sign of potential
problems. For example, in a graphics
editor you shouldn't keep the figures
and the handles in the same
collection, because the figures change
once a minute or once an hour and the
handles change once a second or once a
minute.
In a somewhat larger view, you want a
system to be able to change fast
enough to keep up with the changes in
the business.
PS: the other principle that you should follow is "Law of Demeter", that is, an object should only talk to its friends. Friends are: yourself, instance variables, parameters, locals, and members of friendly collections - but not globals and static variables.
You might consider using the CRC (Class/Responsibility/Collaboration) card approach to OO design. This is nothing too scary - just a way to sort out what your objects should be, and which object should be responsible for which tasks by writing stuff down on a bunch of file cards to help clarify your thoughts.
It was originally designed as a teaching tool for OO thought, and might work for you. The original paper is at: http://c2.com/doc/oopsla89/paper.html
A poster above suggested programming in Smalltalk to force you into OO habits, and to an extent that's a good suggestion - Smalltalk certainly did me a lot of good, but
a) you may not have the spare time to learn a new language. If you do, great.
b) I used to tutor a university course in OO programming, using Smalltalk, and the students did an excellent job of proving that old joke about how "You can write FORTRAN in any language".
Finally: when I was learning about OO (from books) I got the impression that you subclassed a lot, creating complicated class hierarchies. When I started working with OO programmers I realised it didn't happen as often as I thought. I think everyone makes this mistake when they're learning.
The only way to write better code is to write more code. Take a project you've implemented procedurally and convert it to OOP (assuming you're working in a language that supports both). You'll probably end up with a fragile, tightly coupled solution the first time around, but that's ok. Take the bad OOP implementation and start refactoring it into something better. Eventually, you'll figure out what works, and what doesn't.
When you're ready to take the next step, pick up a Design Patterns book and learn some of the OOP design terminology. This isn't strictly necessary, but it will give you a better grasp of some of the common problems and solutions.
I think you should convince yourself by researching all of the downsides with procedural programming, for example (some buzzwords following, watch out): scope, state ... practically you'd be able to extract many terms just by reading examples of design patterns (read: common examples of using objects together.)
Stressing yourself into learning something you don't believe in won't get you anywhere. Start being really critical on your earlier work and refactor it to avoid copied code and using the global scope, and you'll find yourself wanting more.
For me the ah-ha moment of OOP was the first time I looked at code and realised I could refactor common stuff into a base class. You clearly know your way around code and re-use, but you need to think around classes not procedures. With user authentication it's clear you're going to have a username and password, now they go into the base class, but what if you need a tokenId as well, re-use your existing login base class, and create a new subclass from that with the new behaviour, all your existing code works without change.
See how that works for you.
Well, first off design patterns are about the worst thing to pattern your programming to.
It's just a big set of things. It's nothing to do with OOP, and most of them such as singleton are constantly used for all the wrong reasons (ie initialization). Some of these things you have to use so telling you about them is pointless, others are counterproductive, and the rest are just special case things. If you try to learn anything this way everything will start to look like some bizarre doodad someone came up with for a very special problem or because they needed infinite genericity (which is seldom true). Don't let people con you into using a million iterators and templates for no reason and make things ten times more complicated.
Really OOP is a simple subject that gets massively overcomplicated. Unfortunately in C++ it has a lot of issues but really simple virtual methods are what matters. Pure virtual base classes used much like a java interface object are the most useful but also just plain virtual methods here and there will come in handy.
It's mostly been overblown. It also doesn't lend itself well to every problem. If you make database and gui stuff it lends itself well to that. If you make system tools it is usually not as helpful.
I found that one of the things which has really helped solidify the benefits of OOP for me has been writing unit tests with a mock object framework (such as EasyMock). Once you start to develop that way, you can see how classes help you isolate modules behind interfaces and also allow for easier testing.
One thing to keep in mind is that when people are first learning OOP, often there is an overemphasis on inheritance. Inheritance has its place, but it's a tool that can easily be overused. Composition or simple interface implementation are often better ways of doing things. Don't go so far in attempting to reuse code via inheritance that you make inheritance trees which make little sense from a polymorphism standpoint. The substitution principle is what makes inheritance/interface implementation powerful, not the fact that you can reuse code by subclassing.
A great step would be to start of with a OOP framework, you can still write procedural code in the framework but over time you can refine your coding habits & start converting functionality into objects.
Also reading about patterns & data modeling will give you more ideas about to code your logic in a OOP style.
I have found that a very intense way learning to train abstraction in programming is to build a OOP library with a defined functionality, and then to implement two projects with similar but still different requirements that are building on that library, at the same time.
This is very time-consuming and you need to have learned the basics of OOP first (S.Lott has some great links in the other answer). Constant refactoring and lots of "Doh!" moments are the rule; but I found this a great way to learn modular programming because everything I did was immediately noticeable in the implementation of one of the projects.
Simply practice. If you've read everything about OOP and you know something about OOP and you know the OOP principals implemented in your language PHP... then just practice, practice and practice some more.
Now, don't go viewing OOP as the hammer and everything else as the nail, but do try to incorporate at least one class in a project. Then see if you can reuse it in another project etc..
Learn a new language, one that helps to move you gently to OOP. Java is nice, but a bit bloated, though. But its system library is mainly OO, so you are force to use objects.
Moving to another language also helps you not to reuse your old code :-)
I think it´s important to learn the theory first. So reading a book would be a good start.
I believe that the mechanics of OOP seem completely arbitrary and make no sense until you read a book on design patterns and understand the "why" of it. I recommend Head First Design Patterns. I thought OOP was ridiculous and completely useless until I picked up this book and saw what it was actually good for.
OO makes a lot more sense when you understand function pointers and how it relates to indirect function calls and late binding. Play around with function pointers in C, C++, or D for a little while and get a feel for what they're for and how they work. The polymorphism/virtual function part of OO is just another layer of abstraction on top of this.
Procedural is the right tool for some jobs. Don't act like it's wrong. IMHO all three major paradigms (procedural, OO, functional) are valuable even at a fine-grained level, within a single module. I tend to prefer:
Procedural is good when my problem is simple (or I've already factored it enough with functional and OO that I now have a subproblem that I consider simple) and I want the most straightforward solution without a lot of abstraction getting in the way.
Object-oriented is good when my problem is more complex and has lots of state that makes sense in the context of the problem domain. In these cases the existence of state is not an implementation detail, but the exact representation is one that I prefer to abstract away.
Functional is good when my problem is complex but has no state that makes sense at the level of the problem domain. From the perspective of the problem domain, the existence of state is an implementation detail.

What are the benefits of OO programming? Will it help me write better code? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I'm a PHPer, and am not writing object-oriented code.
What are the advantages of OO over procedural code, and where can I learn how to apply these ideas to PHP?
It doesn't help you automatically. You can write worse "OO" programs than structural programs, and vice versa. OOP is a tool which allows you to create more powerful abstractions.
As with every powerful tool, you have to use it properly.
As with every powerful tool, it takes time to learn how to use it properly.
As with every powerful tool you will make mistakes.
As with every powerful tool you will have to practice a lot.
As with every powerful tool you should read a lot about it, and read what other people think. Learn from others.
But, as with every powerful tool, there are people out there who misuse it. Learn to not learn bad practices from them. This is hard.
Objects help keep your code isolated between different sections, so that if you need to make a change to one section you can be confident it won't affect other sections: loose coupling.
Then, when you've done that for a while, you'll start finding that objects you created for one app are also useful in others, and you start getting better code re-use as well. So the new app has part of the work already done, and is using time-tested code: software is built faster with fewer bugs.
People will tell you various things about OOP, from various perspectives. But if you want to form your own opinion, rather than take someone else's, then I suggest reading Bertrand Meyer's "Object-Oriented Software Construction".
Essentially, he takes non-OOP programming techniques, and analyses their basic flaws. He then derives an alternative technique which addresses those flaws. Put another way, he derives OOP from first principles. It's a marvellous piece of work, and very convinving.
Read it, you'll learn the why, when and what in a way that you can back up with reasoning.
Objects help encapsulate complexity. For most PHP programming, it's impossible to write good, clean code for any reasonably complicated application. Writing OO PHP helps you put that code into its own box, isolating it from everything else. This has several benefits.
As long as your object has clearly defined inputs and outputs, the way that the object does what it does doesn't matter at all - storing/retrieving data could go from flat file to XML to memcache to MySQL to Oracle, and you only ever have to concern yourself with one single object.
As long as your object has clearly defined inputs and outputs, you can completely replace it with another object that has the same inputs/outputs. Decide at runtime whether you want MySQL, Postgres, memcached, or HTTP POST/GET requests to a sketchy server in Indonesia.
OO makes unit testing easier. If you can define what a specific object should do (i.e what results it should give you for a given input) then you can easily write code to test thousands of values against that code and check the results, and you'll know instantly if something breaks.
The more of your code you 'hide' in objects, the less of it you have to see when you're using that functionality. I wrote a polling application once in PHP that handled all aspects of polling - database interaction, poll generation, voting, ranking, sorting, and displaying - and I only needed one line of code on my website (Poll::Display()) to implement the entirety of what the app could do - which made maintaining my homepage far easier.
Keep one thing in mind - OO in PHP (even PHP5) isn't very good OO compared to a language like Python or Ruby. The everything-is-an-object model in Python is what made me OO programming really click for me - and as a former PHP programmer (and doubly-certified Zend engineer), I strongly recommend exploring Python's OO if you want to understand what OO is all about. It will help you write better PHP code, at the very least.
Yes, if you really get it.
It helps you visualize how parts of a larger system can interact with each other. It's very useful at the design level.
If you are just writing a few lines of code, the only benefit you will get is that it is generally a little easier to use a library broken into well-designed objects than just functions.
To make good use of it, you also need to follow sound OO design practices. Always encapsulating ALL your data, using many small classes, never large "catch-all" classes. Having the class do your work for you instead of asking it for data and doing the work outside the class, etc.
It's probably not going to help you much for a while, and possibly never if you are always doing small websites (I can't say this for sure, I don't really do php), but over time and on large projects it can be invaluable.
One thing no one has mentioned is that OO code facilitates writing readable code:
sherry.changePhoneNumber();
phoneCompany.assignNewPhoneNumberTo(sherry);
sherry.receive(new PhoneNumber().withAreaCode("555").withNumber("194-2677"));
I get a strange satisfaction from such aesthetics.
The huge win for me is inheritance, or making an object that behaves almost exactly like another but with a few differences. Here's a real-world example from my office:
We needed code to process TIFF files that a customer sent to us, convert them to a standard format, insert some information about the file into a database, then send a result email. I wrote this in a set of classes (in Python, but the idea is the same). The "fetcher" class got emails from a POP3 mailbox and handed them to a "container" class which knew how to read attachments from an email. That class handed each image off to a "file object" class that did the necessary processing.
Well, one day we got a customer who wanted to send PDF files. I subclassed the "TIFF file object" class and rewrote the "normalize" function to take a PDF as input instead, but left every other bit of code untouched. It worked the first time and I was pretty pleased.
A change to our mailserver meant that I needed to fetch emails via IMAP. Again, I subclassed the "POP3 fetcher" so that it could speak IMAP. Problem solved.
Another customer wanted to mail us CDs, so I subclassed the "email container" class with a "filesystem directory" class. Voila - done.
In each of those cases, the new code was 95% similar to the old code. For example, the "TIFF file object" class has about 15 methods. The "PDF file object" class defines exactly one: the method that converts files in a specific format into our standard. All others it gets from its parent class.
Now, you can definitely do the same kind of stuff procedurally, such as by writing:
if fileobjecttype == 'TIFF':
data = <snip 30 lines of code to read and convert a TIFF file>
elif fileobjecttype == 'PDF':
data = <another 45 lines to read a PDF>
elif fileobjecttype == 'PNG':
data = <yep, another one>
The biggest difference is that I believe you can make OOP look much cleaner and more organized. My PDF class looks like:
class PDFReader(GenericImageReader):
def normalize(self):
data = <45 lines to read a PDF>
and that's it. You can tell at a glance that it only does one thing differently than the class it inherits from. It also forces you - or at least strongly encourages you - to make clean interfaces between the layers of your application. In my example, the PDFReader has no idea and doesn't care whether its image came from a POP3 mailbox or a CD-ROM. The POP3 fetcher knows absolutely nothing about attachments, since its job is merely getting emails and passing them along. In practice, this has allowed us to do some pretty amazing things with the absolute minimum amount of coding or redesign.
OOP isn't magic, but it's a pretty fantastic way to keep your code organized. Even if you don't use it everywhere, it's still a skill that you really should develop.
There was a time, back when i first started programming, that i wrote user-oriented code. It worked great, but was hard to maintain.
Then, i learned OO, and the code i wrote become easier to maintain, easier to share between projects, and life was good... for everyone except my users.
Now, i know the true silver bullet of computer programming. I write OO code, but first i objectify my users. Treating people as objects may seem rude at first, but it makes everything much more elegant - you get to write all of your software to work with clearly-defined interfaces, and when a user sends an unexpected message you can merely ignore it, or, if marked with a flag signifying sufficient importance, throw an exception at them.
Life, with OO, is good...
I would argue that OOP suits those who think in 'objects', where an object consists of data as well as the functions that operate on that data.
If you tend to think of functions and the data they operate on as separate things, then you are a procedural programmer.
If you tend to think of functions and the data they operate on as being connected, then you are an object-oriented programmer.
I'd caution against going out and learning about patterns. In order to do object-oriented programming well, you need to teach yourself to think like an object-oriented programmer. You'll need to get to the point where you understand and can name the benefits of:
Encapsulation
Classes vs instances/objects
Inheritance and polymorphism
It will help you to be a better programmer only in the sense that the more styles of programming a programmer knows, the more range in his repertoire for solving problems and writing elegant code. You cannot go off and write all your code object-oriented and automatically have good code, but if you really understand how OOP works, and you're not just copy-pasting some popular design patterns of the day, then you can write some pretty good code, especially when writing a large application.
It seems everybody is responding to your question literally, i.e., the specific benefits/drawbacks of OO.
You should learn OO, but not because OO has any specific magic that you need.
The more general form is:
Q: "Should I learn (OO, FP, concurrent, logic-based, event-driven, ...) programming?"
A: "Yes, learning a new paradigm is always useful, even if you don't use it directly every day."
I would put it this way: If you write anything complex, you should encode the concepts you think in, rather than trying to think in concepts that are somehow native to the language you are using. This way you make less bugs. The formalization of those concepts is called design.
Functional programming lets you define concepts that are associated with verbs, since each function is essentially a verb (e.g., print()). OO programming, on the other hand, lets you also define concepts associated with nouns.
To elaborate on Joeri's answer a little:
The International Organisation for Standardization defines encapsulation as, 'The property that the information contained in an object is accessible only through interactions at the interfaces supported by the object.'
Thus, as some information is accessible via these interfaces, some information must be hidden and inaccessible within the object. The property such information exhibits is called information hiding, which Parnas defined by arguing that modules should be designed to hide both difficult decisions and decisions that are likely to change.
Note that word: change. Information hiding concerns potential events, such as the changing of difficult design decisions in the future.
Consider a class with two methods: method a() which is information hidden within the class, and method b() which is public and thus accessible directly by other classes.
There is a certain probability that a future change to method a() will require changes in methods in other classes. There is also a certain probability that a future change to method b() will require changes in methods in other classes. The probability that such ripple changes will occur for method a(), however, will usually be lower than that for method b() simply because method b() may be depended upon by more classes.
This reduced probability of ripple impacts is a key benefit of encapsulation.
Consider the maximum potential number of source code dependencies (MPE - the acronym is from graph theory) in any program. Extrapolating from the definitions above, we can say that, given two programs delivering identical functionality to users, the program with the lowest MPE is better encapsulated, and that statistically the more well-encapsulated program will be cheaper to maintain and develop, because the cost of the maximum potential change to it will be lower than the maximum potential change to the less well-encapsulated system.
Consider, furthermore, a language with just methods and no classes and hence no means of information hiding methods from one another. Let's say our program has 1000 methods. What is the MPE of this program?
Encapsulation theory tells us that, given a system of n public nodes, the MPE of this system is n(n-1). Thus the MPE of our 1000 public methods is 999,000.
Now let's break that system into two classes, each having 500 methods. As we now have classes, we can choose to have some methods public and some methods private. This will be the case unless every method is actually dependent on every other method (which is unlikely). Let's say that 50 methods in each class is public. What would the MPE of the system be?
Encapsulation theory tells us it's: n((n/r) -1 + (r-1)p) where r is the number of classes, and p is the number of public methods per class. This would give our two-class system an MPE of 499,000. Thus the maximum potential cost of a change in this two-class system is already substantially lower than that of the unencapsulated system.
Let's say you break your system into 3 classes, each having 333 classes (well, one will have 334), and again each with 50 public methods. What's the MPE? Using the above equation again, the MPE would be approximately 482,000.
If the system is broken into 4 classes of 250 methods each, the MPE will would be 449,000.
If may seem that increasing the number of classes in our system will always decrease its MPE, but this is not so. Encapsulation theory shows that the number of classes into which the system should be decomposed to minimise MPE is: r = sqrt(n/p), which for our system is actually 4. A system with 6 classes, for example, would have an MPE of 465,666.
The Principle of Burden takes two forms.
The strong form states that the burden of transforming a collection of entities is a function of the number of entities transformed. The weak form states that the maximum potential burden of transforming a collection of entities is a function of the maximum potential number of entities transformed.
In slightly more detail, the burden of creating or modifying any software system is a function of the number of program units created or modified.
Program units that depend on a particular, modified program unit have a higher probability of being impacted than program units that do not depend on the modified program unit.
The maximum potential burden an modified program unit can impose is the impacting of all program units that depend on it.
Reducing the dependencies on an modified program unit therefore reduces the probability that its update will impact other program units and so reduces the maximum potential burden that that program unit can impose.
Reducing the maximum potential number of dependencies between all program units in a system therefore reduces the probability that an impact to a particular program unit will cause updates to other program units, and thus reduces the maximum potential burden of all updates.
Thus, encapsulation is a foundation stone of object orientation and encapsulation helps us to reduce the maximum potential number of dependencies between all program units and to mitigate the weak form of the Principle of Burden.
I'm a long-time procedural PHP programmer who occasionally dabbles in object oriented PHP. Joel's answer above is an excellent summary of the benefits. In my opinion, a subtle secondary benefit, is that it forces you to better define your requirements from the start. You have to understand the relationships between the objects and the methods that will be acting upon them.
A good book to help with the transition is Peter Lavin's "Object-Oriented PHP".
A large system, such as Wordpress, Drupal, or XOOPS, uses OOP concepts. You can see the benefits of their use there. Code reuse, modularity, maintainability, and extensibility.
You have the ability to modify parts of objects and it affects the entire application; no searching to replace every spot you did some operation (and possibly missing it).
You can reuse objects all over, saving an awful lot of copying and pasting. Patching a bug requires patching the one object, not 16 pages of code that all do the same thing.
When you encapsulate the logic and "hide" the implementation, it's easier to use the objects, both for you 6 months from now when you've forgotten why you did something, and for the nest guy or gal who uses your code. For example, all you do to loop through posts in Wordpress is call a function. I don't need to know how it works, I only need to know how to call it.
OOP is really procedural code wrapped in object methods/functions. You do still need to know how to write decent linear code in order to implement methods and functions of objects. It just makes it far easier to reuse, scale, fix, debug, and maintain your things.
http://www.onlamp.com/pub/a/php/2005/07/28/oo_php.html
I would say there are two primary benefits:
Encapsulation: code in libraries that shouldn't be called from outside the library can be hidden, preventing misuse, and easing changes to the internal structure of the library while preserving the external interface. In a good OO design, changes are introduced more easily once the code is complete.
Abstraction: instead of dealing with arrays of arrays you're dealing with employees, departments, and so on. This means you can focus on the business logic, and write fewer lines of code. Fewer lines means fewer bugs.
Reuse I wouldn't strictly qualify as an OO benefit, because in a purely procedural model smart library organization lets you reuse code as well.
On the other hand, using lots of objects in PHP tends to decrease performance compared to a procedural model, because there is too much object construction overhead for every request. Finding a good balance between procedural-style and oo-style code is imperative.
To learn OO in PHP I'd recommend try to use some good written OO PHP framework.
You may want to look at Zend Framework.
I am a PHP aswell, although I do have a strong OOP background, I would say the best book on using OOP with PHP has to be PHP 5 Objects Patterns and Practice
One of the best thing that I did with OOP in PHP is the class generator.
In any given table, it will involve almost the same SQL operations:
insert
update
select
delete
exists (check if a row exists)
search
list
Now I don't have to write all these SQL statements anymore, except on special conditions. Not only I've cut down coding to 1 minute in doing above, I've also saved time from debugging codes.
So whenever there are changes to the table structure, I simply regenerate the class.
Probably you should try the same as it works for me and my customers like it!

PHP Object Oriented or not? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I have a start of a webapp that I wrote without using the Object Oriented features of PHP.
I don't really know if it is worth it to go back and rewrite the parts I have finished. Is object oriented PHP worth rewriting all or part of a decent working app?
Given that you have an incomplete app I would say that reworking it into an Object based app will probably be helpful.
One thing to consider is the expected size of the end application. Below a certain complexity Object based may be overkill except for the learning experience.
I started out avoiding Objects like the plague because my initial introduction to them in university classes was terrible. I somewhat recently had to work on a project which was implemented in php objects. making the required changes was much easier than other projects. I have since then worked in the object model frequently and find it very handy for quick creation and easier upkeep.
Just to disagree with the consensus... I would say no in most cases. Not as an academic exercise on commercial code anyway. If it's working don't re-write it. If you have to go in to change / add bits, then refactor towards OO practices (there are lots of posts on SO about refactoring when you are changing code anyway, and not just for the sake of it).
In practise if you haven't done a lot of OOP, then you'll want to start small and get a feel for it.
Once you get a handle on the basics, a good beginners guide to Design Patterns (I like the Head First book) is very useful. Most PHP books would teach you OOP fairly poorly. They teach you about inheritance, but usually don't teach you about loose coupling and favouring composition over inheritance. A design patterns book will give you a better insight into this.
PHP still has a reputation for not "doing" OO right. I don't think this is fair, but is a reflection of the fact that it's so easy for people to get started without really grokking OOP. I would go out on a limb and say the majority (ever so slightly - call it 51%) of PHP programmers aren't comfortable with OOP. I think it's possible to do good OO in PHP, and if you're already comfortable with the language it's a great way to grow your skills.
EDIT:
Just to add a couple of disclaimers...
My comment about most PHP programmers not being comfortable with OOP wouldn't apply to the current SO audience!
Not suggesting you aren't comfortable with OOP, this applies if you're not
Typical answer: "It depends."
I tend to write the display page as a start-to-finish, < html > to < /html > scripted page. But the things that happen on that page were objects. Kinda like a poor man's ASP. While you can have OOP-base output, I alwasy thought it too cumbersome for a task as tedious as dumping data to a browser.
So, business rules and data access were OOP. Presentation was script.
If you have business rules that are not OOP, I would seriously consider writing those as objects on two conditions: (1) is "Do you have time/effort/money to do so?" and (2) is "Do you have a good PHP IDE that will make your life easier?" If it works, and changing it means writing in Notepad++, then I would call it done. :-)
I wouldn't say it is critical, but if you are going to go much further with the app, I would recommend doing it now while it is not as much of a monumental task. I would say the maintainability of a well written OOP program could far outweigh the up front costs. Especially when you consider that you will be able to refactor much of the code as you go along.
Learning object oriented techinques will be really useful, especially for programming in other languages in the future.
Since you have only just started the application, you could rewrite and improve the parts you have written. It depends on your deadline.
There are two possibilities: either your app is a one-off that just has to work right now and will never be touched, adapted, expanded or modified, or else your app is the beginning of something that you will keep working with and using over a long time.
If the former, don't break perfectly usable code. You have better things to do with your time.
If the latter, you have to bear in mind an important fact about PHP, which is this: poorly written PHP is a nightmare to maintain. Not as bad as poorly written Perl -- because what is? -- but bad enough that sooner or later you will feel a strong urge to steal a time machine, travel back to the moment you wrote the code you now find yourself maintaining, and stab yourself in the eye socket with an icepick.
So if you're going to be maintaining this code over time, take the time to do it right. That means: some kind of templating system, no PHP tags embedded inside HTML, separate files for separate functionality, and classes classes classes!
Your eye sockets will thank you.
I would say try and go OO just because what you have can be reused much easier than procedural if done right
I will also say that OO is much more organized then procedural. When your at a small scale it's easy to get away with sloppy code OO or not. But when you get to larger projects your procedural must be much more organized and thought out. Where as on some larger projects OO tends to force you to be more organized making things a little easier.
No, i think if the app is working like it should there's no need to rewrite it.
PHP isn't really OOP at all. They try hard but sometimes i think even the PHP-Developers dont really understand the sense of OOP.
If you wish to learn OOP (which is surely a good idea) try a real OOP-language like Smalltalk to learn the basic concepts. Java is also nice 2 learn the basic, although it isnt fully OOP as well
I'd like to reiterate the other answers here. It depends upon size of application and how much you'd like to learn about OOP. I'd be careful of learning OOP by using PHP though.
As for how much PHP is object oriented... PHP4 had some OOP elements slapped onto it, PHP5 is better but it's not baked into the language. PHP works both ways, and personally I like that you can choose.
In my mind, we phper can thorouly throw away the concept of Object(class instance), we only need Array and Mode Class:
All arrays in initial mode support any array function as it's method:
<?php
$array1->array_flip(this);
?>
Use ->mode() to validate the minimal data set, and then switch mode class:
<?php
$array1->mode('class1', $success);
?>
Any mode class has no ->construct() in it, but has ->validate() to validate the minimal data set.
The array in a mode still could use array function as its method, but after using any of them the array will be switched back into basic array mode,
and we need to use ->mode('class1', $success); to switch mode back.
The radical thought is data-centric programming, we need separate the data(array) and the activity(class method).
We could modify PHP engine, to get rid of parts of OO(object oriented), and support Mode Class, we could call it MyPHP.
For example:
$array_man1 could be set into two modes:cls_normal_man and cls_crazy_man:
<?php
$array_man1->mode('cls_normal_man')->normal_method1()->mode('cls_crazy_man')->crazy_method1();
?>

Categories