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...
Functions do specific things, classes are specific things. Classes often have methods, which are functions that are associated with a particular class, and do things associated with the thing that the class is - but if all you want is to do something, a function is all you need.
The main reason people use classes (that I've read) is for re-usability, but you can call a function any number of times. The main other reason I've seen is because you can create different instances of classes, but you can call functions with different parameters.
One of the big differences between functions and classes is that a class contains both data (variables) and functions that form a package called an: 'object'. Class is a programmer-defined data type, which includes local methods and local variables. Class is a collection of objects. Object has properties and behavior.
A key benefit of using functions is that they are reusable; if you have a task that needs to be performed a number of times, a function is an ideal solution. They can be either defined by you or by PHP (PHP has a rich collection of built-in functions).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With