php – OOP – Does it make sense to write a class that has no properties but has a method?


Does it make sense to write a class that has no properties but a method? Or is it enough to use a custom function in this case?

 class Text { public function MultiColor(){ static $a = null; $a ++; return $a; } } echo Text::MultiColor();


Let's figure it out.

First, the OOP paradigm itself does not imply the use of other paradigms. This is not a ban on their joint use, however, the paradigm itself is self-sufficient, although it is often not implemented in its pure form (functions in PHP and Python, primitives in Java and C #), and partial replacement of the paradigm will lead to a decrease in the consistency (uniformity) of the code.

The OOP paradigm includes two components in an object: behavior (methods) and state (properties). This case discusses stateless behavior (which isn't really true – $a is stateful because it persists between calls), and it's indeed a bit confusing, but don't be fooled. OOP allows you to include both behavior and state in objects, but does not prohibit you from excluding any of these from the object; in other words, a class that declares stateless functionality, as well as objects that simply transfer data (Business Object, Data Transfer Object) are absolutely valid units of the program.

And, of course, it is necessary to say a few words about statics. The paradigm itself does not imply the existence of classes and static methods. However, methods that work without a state, the very place in the static – firstly, they do not need an extra instance of the object to work, and secondly, this emphasizes the detachment of the method from the state. However, be careful: declaring static variables usually indicates that it's time to create a regular stateful object; the only really rational example I can think of for storing something in a static variable is the logger in Java.
True, I myself am an ardent opponent of statics in principle, but this is a completely separate topic for conversation.

And finally: a good paradigm does not prohibit the user from doing anything. It only describes the concepts within which it should be convenient for the user to build a project.

In summary: yes, using stateless methods is absolutely legal, but beware of transferring to static what should be in regular methods.

Scroll to Top