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?
When to define static methods ? The static keyword is used in the context of variables and methods that are common to all the objects of the class. Therefore, any logic which can be shared among multiple instances of a class should be extracted and put inside the static method.
You should consider making a method static in Java : 1) If a method doesn't modify the state of the object, or not using any instance variables. 2) You want to call the method without creating an instance of that class.
PHP Traits are Good Regardless of the unanswered questions, traits are great for PHP, allowing us to create multiple inheritance scenarios (extends only supports single inheritance).
Traits are a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With