views:

272

answers:

2

I'm under the interpretation that if I need to access a method statically, I should make the class abstract only if I'll never need it instantiated. Is that true?

+3  A: 

I'm a little unsure of the question. Static methods are quite different from abstract classes. Usually you'll make an abstract class if you don't want a class instantiated, but you expect sub-classes to be instantiated. Using abstract classes can be very helpful to create a partially-implemented class where sub-classes will fill out the rest of the methods to fully implement the class.

A class full of static methods can be declared abstract if you want to prevent usage of the class, but generally I would say that if you mark a class abstract, you should be able to find classes that extend the class. If I have a class that is full of static methods I do not label it as abstract because nobody will subclass it, and it generally adds confusion. I'd rather it be called a static class, not abstract.

Kekoa
Definitely; the semantics of abstract vs. having a private constructor are very different, and using the correct one gives a strong hint to anyone reading the code as to how the class is used.
Rob
+3  A: 

PHP does not have static identifier on classes, so other methods are needed to prevent one from being instantiated.

You can prevent a class from being instantiated by defining it abstract, and it is a cheap way to do so, although that's not the purpose of an abstract class.

Other methods include defining the contructor private

private function __construct() {}

Or throwing an exception in the contructor if you wish to give a more meaningful message as to why it can't be instantiated.

function __construct() { throw new Exception('This is a static class'); }

If you also do not want the class subclassed declare the class final.

final class foo { }

Or in the odd case you want to be able to subclass it, but not allow any of it's children to instantiate declare the constructor final. (Far fetched situation, but for completeness)

final private function __construct() {}
stroop