Artur
Artur

Reputation: 13

Using classes in PHP to store function

I need some advise on my PHP code organisation.

I need classes where I can store different functions, and I need access to those classes in different parts of my project. Making an object of this classes each time is too sadly, so I've found a two ways have to solve it.

First is to use static methods, like

class car {
public static $wheels_count = 4;

public static function change_wheels_count($new_count) {
    car::$wheels_count = $new_count;
} }

Second is to use singleton pattern:

class Example {
// Hold an instance of the class
private static $instance;

// The singleton method
public static function singleton() 
{
    if (!isset(self::$instance)) {
        $c = __CLASS__;
        self::$instance = new $c;
    }

    return self::$instance;
}  }

But author of the article about singletons said, that if I have too much singletons in my code I should reconstruct it. But I need a lot of such classes.

Can anybody explain pros and cons of each way? Which is mostly used? Are there more beautiful ways?

Upvotes: 1

Views: 121

Answers (2)

erisco
erisco

Reputation: 14329

When you say that you need to use a class of some sort to store functions, I am presuming that you'd normally be fine using plain functions but you do not want to pollute the global scope. This problem you will run into all the time in PHP.

If you are lucky to be working with PHP 5.3 you can use namespaces to pull the functions out of the global scope. Effectively, namespaces serve as a convenient way to auto-complete the prefixes you would normally have on functions to try and ensure their uniqueness. Because of this primitive implementation, there is no access control available for namespaces. If you wish to design an interface, you are out of luck, as all functions are globally accessible.

In this case, use a static class. No, it is certainly not the most beautiful solution but it is literally the best PHP can offer. With a static class you can effectively both prefix your functions for uniqueness and use access control.

Singletons are an object-oriented concept that solve a different problem. If your original design involves no objects, don't introduce them now.

That said, you have a function called change_wheels_count(). This function has a notion of state, and whenever you need state you need an object. I do not know if your code was just a quick example or your actual situation. If it was your actual situation, I would say you need neither a static class or a singleton.

Upvotes: 0

Sarfraz
Sarfraz

Reputation: 382736

See this excellent post:

Singleton Pattern vs Static Classes

More Resources:

How Bad Are Singletons?
Static DB class vs DB singleton object

Upvotes: 1

Related Questions