Greggg Greggg - 2 months ago 26
PHP Question

PHP: When to use Traits and when to use static methods?

My PHP applications are generally using classes for namespacing. The methods within these classes are defined as static.

Now that PHP has introduced Traits, I'm trying to wrap my head around when to use them. I saw some examples of using traits, but I'm thinking this could just as easily be implemented through a static class method.

A quite thorough example using a logger was listed here: traits in php – any real world examples/best practices?

But why use a Trait, if you could also use a static Logger::log()? The only thing I can think of just now, is easy access to $this.
Another example I am facing right now, is a user-exists function. Trait it, or static method it?

Can anyone shed some light on this?


After reading the comments on the question, my take on the answer is this:

Traits allow the extending of a class without it being part of the class hierarchy. There's no need for something like class Book extends Loggable, as Book itself is not a Loggable, we just want the Loggable functionality. The functionality within the Loggable could be stuffed in a trait, therefore being able to use the Loggable methods within Book as though you were extending from it.

The advantage of using traits above the use of static methods within classes (or namespaced functions) is that the trait has access to the full class scope, also private members.

The downside of using static functions instead of traits, is tight coupling (dependencies) between the classes, which hurts reusability and can hurt unit testing (for instance when using mock services). Dependencies should be injected at runtime, which indeed increases the effort of instantiating a class/method, but allow better flexibility over the full app. This was a new insight for me.