1

I have a class in PHP which only has static methods. Is it appropriate to prevent this class from being instantiated, and if so how should it be done? (by "appropriate", I mean intended usage balanced with pros and/or cons.)

AFAIK, creating an instance of it wouldn't hurt or cause any problems aside from the fact that it is completely pointless.

Also, AFAIK, the way this can be accomplished is by making the constructor private or making the class abstract. Making the constructor private seems hacky since it's not that I want the constructor to be used only from within the class, it's that I want construction itself to be impossible. And making it abstract also seems wrong and hacky since it's intended for direct use.

StubbornShowaGuy
  • 249
  • 4
  • 18
  • 1
    To me, making the constructor private is not really hacky as you said. If not a single function on your class use the constructor, then the class won't be instantiated. – Treast Oct 20 '16 at 04:10
  • 1
    You could try [`trigger_error()`ing](http://php.net/trigger_error) from inside the constructor. If the point of this exercise is to communicate to a fellow developer that the class should not be instatiated, an error should grab their attention. –  Oct 20 '16 at 04:13
  • @Terminus Sorry, maybe the explanation was a bit vague, I understand how it _can_ be done, but the main thing that I don't understand is how I am _suppose_ to do this. Obviously(or maybe I should say hopefully?) the person/people who made the programming language has a vision or a policy on how things should be done, and I think (and/or hope) it covers use of classes that has nothing but static methods. – StubbornShowaGuy Oct 20 '16 at 04:21
  • @StubbornShowaGuy I gotcha. Here's a [question&answer](http://stackoverflow.com/questions/1942903/is-it-bad-practice-for-a-class-to-have-only-static-fields-and-methods) that's for OOP in general. Interesting for php too, imo. –  Oct 20 '16 at 04:28
  • 1
    @Terminus Thank you. Although it doesn't provide a definite answer, that's insightful. It's not PHP, but the top-rated comment to the question, "`java.lang.Math` is 100% static methods with a private constructor (can't be instantiated)." got me leaning in the direction of "making the constructor of classes with only static functions private is an accepted practice". – StubbornShowaGuy Oct 20 '16 at 04:45

0 Answers0