When to use static modifier in PHP
Asked Answered
Z

8

35

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?

Zelikow answered 22/8, 2009 at 19:21 Comment(2)
No one has answered the last question till now -- "Do they affect performance or memory footprint?" Static's are generally discouraged in Java. Not sure this is also true for interpret language like PHP.Expositor
if you are doing OOP (as you have tagged), then never: #5168160Interstice
T
22

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)

Tung answered 22/8, 2009 at 19:48 Comment(1)
Organizing related functions as statics in classes also explore a powerful feature on PHP: The ability to autoload classes on demand. If allows you to write your code without worrying about doing the proper includes, and without need to include something you might not always use. You simply call your static method and the __autoload() does its magic. Clean, optimized and functional coding. Not even namespaces got that one yet.Raffo
V
7

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.

Vole answered 13/1, 2012 at 6:36 Comment(7)
I've seen these arguments before, but they're not compelling. The way you make static methods testable is by having no side effects; such methods are the most testable of all; you give them an input, they return an output, that's it. The hard dependency on a class argument carries no weight either; grouping related static methods together in a class is the whole point.Managing
You didn't address the crux of both of those links -- dependencies. Being able to override depended-on functions is crucial to testing. To be fair, it is possible to do this with static functions (e.g., by taking function dependencies as parameters). However, the idiomatic solution in PHP is to use a non-static function that can be overriden by a subclass. See kunststube.net/static for more elaboration.Vole
Properly written static functions don't have any dependencies, except that which is passed directly into the function. Test the function, make sure it has the expected behavior, then use it in all other tests as-is. The examples provided at your link are a mis-use, as calling the functions more than once can produce different results each time. I don't know; I just don't see the benefit of using static methods that way.Managing
It's not dependencies of statics that are the problem. It's dependencies on statics. From "Static Methods are Death to Testability": There seems to be a common misreading of the original article, where Misko says something like ‘if you use a static in a class, that class is harder to unit test’ and people hear ‘statics are hard to unit test’. It’s the classes ‘infected’ by statics that are hard to test, not the static itself; stevedrivendevelopment.com/2012/08/24/statics-and-unit-testingVole
"in order to write a test for the dictionary, I need to know the implementation details of the static to write my test" -- Game over. A proper use of a static method would not require knowledge of its internal implementation. I think most folks who complain about the difficulties of testing using static methods are often simply using static methods improperly. More here: programmers.stackexchange.com/a/5963/1204Managing
Agreed. Looking closer at that code, it could just as easily be setting this.hasher to a static hashing function, which would solve the testability problem equally as well.Vole
I updated my answer to clarify. To be clear, I still advocate that directly calling static methods without providing for dependency injection is death to testability.Vole
D
5

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)
Dilisio answered 22/8, 2009 at 19:30 Comment(0)
P
4

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.

Presently answered 22/8, 2009 at 19:33 Comment(0)
U
3

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.

Upheave answered 22/8, 2009 at 19:39 Comment(0)
M
2

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.

Malleus answered 5/9, 2012 at 15:20 Comment(0)
R
1

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

Raffo answered 22/8, 2009 at 19:26 Comment(0)
C
1

Whenever a method doesn't need an instance of a class and may need to be used separately from any instance of the class, it should be static, provided it can be safely depended on. An instance of a class can be passed as an argument to a static method, however I would consider this bad practice, as it can create difficult to debug code.

Misusing static methods, can certainly create very hard to test code. If the static method needs to be tested in a unit test with non static methods, then it shouldn't be static. However, if you can fully test the method for all possible edge cases independently from any class instance, then no need to worry about unit testing because the static method can have its own separate unit test.

Another thing you should consider, is dependency injection. Static methods can be overwritten by putting them in a separate namespace. To overwrite the static methods, you can simply swap the namespace to one with your overwritten static methods. However, if you are needing to do this, then it is more likely you are misusing statics.

If a method currently makes sense to be static but may not after future modifications, then it's better to have it as non-static. It needs to be depended on without the risk of it causing bugs. Misusing statics can certainly lead to a dependency nightmare.

A lot of people consider it best practice to avoid static methods, however I disagree because every programming language has loads of build in functions and keywords that are static. We don't rewrite them just because they are static. We simply don't worry about it because we know we can depend on them and if we want to, we can can very easily test them for any possible edge case.

Couloir answered 10/3, 2023 at 4:36 Comment(2)
@peterh I fail to see what the Chinese Cultural Revolution has to do with my answer. Did you accidentally post your comment in the wrong place?Couloir
In other languages, static things are not used any more. Instead, the library/framework allocates a quasi-static thingy on initialization (what might be process start, but also for example, as a user first time logs in). Here is a bit hard to directly communicate with others. You suggested a change of my post on the Security SE. My problem with these frameworks-languages is that they need an unthinkable amount of RAM and initialization time and I think it would be better to get rid all of them.Cassady

© 2022 - 2024 — McMap. All rights reserved.