I understand classes (or how to write them anyway), functions and a very good level of PHP. However, I often see people confused over when to use functions over classes. For me, use a function unless there is a good reason to use a class. Many (semi-programmers or below) seem to use only functions (because they don't understand classes) or mainly classes (because they think they have to).
I have produced a quick-reference guide (for myself) to help me decide whether I should use a function or a class.
The question is: am I right? is this the right way to approach classes?
Use a class when...
(1) You need to remember something in a function (for example how many times you've executed that function in that script or feel variables in the function would be better 'memorised' for other executions of that function during that script).
(2) To group data together, e.g. if you return user data from a database and then update it various times in the script. (If you find you're using lots of arrays to store data that is updated during the script execution then a class may be better).
(3) To group together an entire part of the system (user login, database access etc.)
(4) Use a static class on occasions when you have a few functions that can be grouped together and will only be used a few times on your site (rather than putting them all in a file of all functions that is included on every page).
(5) If someone wants to group together pieces of code and distribute as a read-made solution (like on phpclasses.org) - maybe even if it's just a group of functions (e.g. a complete date/time manipulation class would probably just be a few functions together).
If the requirement doesn't fit with the 5 points above then use a function.
I always use an MVC design so code would not be unnecessarily duplicated regardless of if I used functions or classes.








Bookmarks