I’m writing some utility classes for a PHP app and a lot of them will be singletons. Found myself re-writing the same code over and over, and decided to make an abstract base class Singleton and subclass it. Just want to make sure I’ve done this correctly!
abstract class Singleton
{
private static $instance = NULL;
public static final function getInstance()
{
if(self::$instance == NULL)
self::$instance = instantiate();
return self::$instance;
}
protected abstract static function instantiate();
}
class LogHelper extends Singleton
{
protected static final function instantiate()
{
return new LogHelper();
}
}
Now, if I have done this correctly, I can call LogHelper $LOGGER = LogHelper::getInstance() from anywhere in my codebase, and get a reference to the same instance every time, yes?
You will probably need to define your getInstance() methods as static so that you can access them without having to instantiate the class. Then, you’ll use this:
And, you’ll probably want to define a private constructor: