Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use a Class vs. Function in PHP

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...

like image 680
jay Avatar asked Jan 23 '10 04:01

jay


People also ask

Should I use a class or a function?

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.

When would you use a class over a function?

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.

What is the difference between class and function in PHP?

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.

What is the main benefit of using a function in PHP?

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).


1 Answers

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.

like image 161
Kaleb Brasee Avatar answered Oct 12 '22 17:10

Kaleb Brasee