Home » Php » oop – When to use static modifier in PHP

oop – When to use static modifier in PHP

Posted by: admin April 23, 2020 Leave a comment

Questions:

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?

How to&Answers:

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)

Answer:

The best practice is avoid using them whenever possible, because they kill testability and maintainability. Two great reads that elaborate:

CLARIFICATION: There seems to be a lot of misunderstanding on this issue. Lack of dependency injection is the real problem. Directly calling static methods just happens to be the one of the most common ways of falling into that trap.

Answer:

Static methods are used for

  • functions that are related to the whole collection of objects of the given class (e.g. singleton pattern)
  • functions that are not related to anything, but must be put under a class because of OO (e.g. utility classes)

Answer:

Static method doesn’t require an instance (and may return one instead) and is more or less like a global function except for it is put in class’ namespace (and therefore avoid collisions with other functions) and has access to class’ private members.

So, use it whenever you’re interested in these properties of the function.

Answer:

There is nothing PHP specific about the use of static methods.

Static methods can be called directly on the class – no need for an instantiated object.

So their main use is for methods that are related to the classes functionality, but do not need an existing instance to be of use for other code.

A common example would be a custom comparison method that can be passed to, say, the uasort() function to sort an array of objects of the class’ type.

Answer:

you can use static methods for better performance.
you don’t need to create object for each user that using your web App and creating object with multiple methods and properties is slower and needs much more system resources.

Answer:

You don’t need to create an instance of the class to use its static methods.