Answer the question
In order to leave comments, you need to log in
Why can't construct be overridden when inheriting?
Here is just an example: (php5)
class T{
public function __construct(){}
}
class S extends T{
private function __construct(){
// code
}
}
class S extends T{
private function S(){
// код
}
}
$s = new S();
Answer the question
In order to leave comments, you need to log in
Because when inheriting, you cannot change the accessibility of a function. If you need a singleton, then by definition you cannot inherit from a class with a public constructor. And this is done so that the object of any class inherited from this one is guaranteed to have all the functions of the parent, in particular, the ability to create new objects. Otherwise, the meaning of inheritance is lost.
Here is a good discussion on this topic: https://bugs.php.net/bug.php?id=40880
Alternatively, if you want to wrap some object in a singleton, use delegation and not inheritance
class D
{
public function __construct()
{
}
}
class S
{
private static $instance = null;
public static function getInstance()
{
if (!self::$instance) {
self::$instance = new D();
}
return self::$instance;
}
private function __construct()
{
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question