Question

Considering that is needed to create a library with some common functions, what would be considered a best practice, use a lib file with isolate functions like this:

function utilA(){
    echo 'I am a lib with util A function';
}

function utilB(){
    echo 'I am a lib with util B function';
}

function utilC(){
    echo 'I am a lib with util C function';
}

Or create a class with static methods like this:

class Utils{

    static function utilA(){
        echo 'I am A static method from Utils';
    }

    static function utilB(){
        echo 'I am B static method from Utils';
    }

    static function utilC(){
        echo 'I am C static method from Utils';
    }

}
Was it helpful?

Solution

I would definitely recommend going with a class. It makes your code portable among other benefits, like class properties - something that you normally have to do with global variables in procedural functions. You can also use visibility in a class so the public scope can't access your private/protected methods and properties if you don't want them to.

I would stay away from static methods when possible. They are hard to test and if can make bug tracking cumbersome the more complex the class gets. Instead you may wish to look into dependency injection. Basically you instantiate your utility class and pass it to another class that needs it via constructor or mutator method. (However do not let me turn you completely off of statics. Like sugar, they have their place when used sparingly. If you use them, keep them a simple as possible.)

If you are trying to organize pieces of code into parts though, I would recommend you have a look at namespaces. They can help you organize your utilities and include them with other projects while minimizing any naming conflicts.

Hope that helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top