PHP Methods – Should Utility Methods Be Inside a Class?

classfunctionsmethodsPHPstatic methods

I have been working on a library which contains a large set of functions. For the sake of simplicity, I am going to use just one set as an example.

I am not sure which is the better way, in terms of ease of use and performance, whether I should put those methods provided as individual methods, prepended with the function category, or whether it is better to create a Class containing all the method as static methods.

For Example:

Individual methods: (p.s. this could also be writen without request_ in the function name and using Namespaces instead)

function request_method() { ... }
function request_url() { ... }
function request_useragent() { ... }
....

Classed method:

class Request {
    public static function method() { ... }
    public static function url() { ... }
    public static function useragent() { ... }
    ...
}

Best Answer

The key is to put logically related functions in the same namespace. Prefixing as a "namespace by convention" is a bad idea. Depending on the language this has different meanings.

  • In a language like Java you have no choice you're going to have a utility class.
  • If you're in a language like Haskell, OCaml, or Python, these should be in a module.
  • In C++ you have namespaces for the same purpose.

By doing this you leave the burden of making sure you avoid naming clashes to your compiler. With prefixes you're liable to run into something like compiler_typecheck_ast. Does this refer to the class in the "namespace" compiler_typecheck or is it a function in the compiler namespace that typechecks an ast?