Doing some code reviews lately I came across a number of classes that have significant number of static methods in them... and I can't seem to grasp why? Hence my question:
What are the best practices regarding using static methods in PHP?
When would one want to use them and when would one shouldn't use them?
What are specific difference in how runtime handles static methods? Do they affect performance or memory footprint?
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.
Static class is used for a single instance of that class whereas instantiated class is used when more than one instance is required. Static class contains static variables and static methods whereas instantiated class contains non-static variables and non-static methods.
A static method has two main purposes: For utility or helper methods that don't require any object state. Since there is no need to access instance variables, having static methods eliminates the need for the caller to instantiate the object just to call the method.
The most important reason why static keywords are heavily used in Java is to efficiently manage memory. Generally, if you want to access variables or methods inside a class, you first need to create an instance or object of that class.
Doing some code reviews lately I came across a number of classes that have significant number of static methods in them... and I can't seem to grasp why
PHP didn't have namespaces before 5.3, so all function/variables would be in global scope unless they belonged in some class. Putting them in a class as static members is a workaround for not having namespaces (and that's probably why you saw them in "significant" number)
Generally, they are used for functions that aren't much useful in individual objects, but has some use at class level (as said in other answers)
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