When creating a Singleton in PHP, I ensure that it cannot be instantiated by doing the following:
class Singleton {
private function __construct() {}
private function __clone() {}
public static function getInstance() {}
}
However, I realised that defining a class as ‘abstract’ means that it cannot be instantiated. So is there anything wrong with doing the following instead:
abstract class Singleton {
public static function getInstance() {}
}
The second scenario allows me to write fewer lines of code which would be nice. (Not that it actually makes much of a difference.)
When creating a singleton in PHP, declaring the
__constructand__cloneas private ensures that the class cannot be instanciated from the outside : it can still be instanciated from inside its declaration.When declaring a class as
abstract, it can not be instanciated at all ; not even from inside its declaration.This means your solution would not work : in the second case, your
getInstance()method will not be able to instanciate the class — while it can do so in the first case.