When to use a Class vs. Function in PHP

Solution 1:

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.

Solution 2:

A common thing to do since PHP5 was to create classes that act as libraries. This gives you the benefit of organizing your functionality and taking advantage of class features like __autoload();

For example, imagine you have two functions for encrypting and decrypting data. You can wrap them in a class (let's call it Encryption) and make them static functions. You can then use the functions like this (notice no initialization is needed (i.e. $obj = new Encryption)):

$encrypted_text = Encryption::encrypt($string);

and

$decrypted_text = Encryption::decrypt($string);

The benefits of this are:

  1. Your encryption functionality is grouped together and organized. You, and anyone maintaining the code, know where to find your encryption functionality.
  2. This is very clear and easy to read. Good for maintainability.
  3. You can use __autoload() to include the class for you automatically. This means you can use it like it was a built in function.
  4. Because it is contained in its own class and own file it is reusable and can easily be ported to new projects.