Search code examples
phpnamespacesstatic-class

PHP Static Class or Namespace


I'm wanting to gauge people's opinions on the use of static classes instead of namespaces. I come from a C++ background and am quite fond of its syntax and how it lets you structure code. I recently decided I needed to group my code into logical units instead of just files. For instance I prefer calls like User::login to user_login. So, I did a bit of googling and was relieved to find that PHP has namespaces. My relief didn't last long though, I really don't like the syntax; it adds more mess to my function calls. So, at the moment I'm using static classes to simulate namespaces. Are there any downsides to this?

I found a similar question at PHP Namespaces vs Classes with static functions but there wasn't a whole lot of discussion.

Also, is there a way to avoid the following situation:

class Test {
 public static void myFunc() {
  Test::myOtherFunc();
 }
 public static void myOtherFunc() {

 }
}

I assumed it would be ok to call functions in the same class without specifying the name, but apparently not. Are there any workarounds for that (for instance in C++ there the using keyword).


Solution

  • Coincidentally I've actually been moving into the exact opposite direction:

    1. Use namespaces to organize domain classes (or functions)
    2. Use dependency injection where I would have otherwise used static classes

    The thing with static classes to simulate namespaces is that you can't organize them across multiple files, everything has to be defined inside one file; this may well be up to personal taste.

    The other thing about static classes is that you start without any state and slowly some state management creeps in and you end up with some weird lock-in dependency. State should be reserved for instances. Currently my only notable static class is the site-wide configuration.

    Lastly, self referencing in static classes is explicit, whereas in namespaces it works exactly like C++ would: you specify the function name and it gets looked up within the namespace first.