[SOLVED] When to use a Class vs. Function in PHP

Issue

The lightbulb has yet to go on for this…

I’d really love an easy to understand explanation of the advantage to using a class in php over just using functions.

Here’s a simple example of the thought I’m having now and am wondering if a class is more efficient:

Say I have a mini calendar widget that I’ve built in php. I’m thinking about calling the function miniCal('arrayVars1', 'var2'). But I might do it twice on that page. Do use fewer resources by using a class here, create new instances of it?

What tree should I be barking up here, because I feel like right now the tree is a brick wall…

Solution

Classes are used for representing data as objects. If you’re representing something like a user’s data, or an auction bid, creating a User object or AuctionBid object makes it easier to keep that data together, pass it around in your code, and make it more easily understandable to readers. These classes would have attributes (data fields like numbers, strings, or other objects) as well as methods (functions that you can operate on any class).

Classes don’t usually offer any benefits in terms of performance, but they very rarely have any negative effects either. Their real benefit is in making the code clearer.

I recommend you read the PHP5 Object-Oriented Programming guide and the Wikipedia OOP entry.

Answered By – Kaleb Brasee

Answer Checked By – Clifford M. (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.