D
D
Dmitry2015-09-12 11:52:57
PHP
Dmitry, 2015-09-12 11:52:57

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
  }
}

The swearing is due to the fact that php does not want to make it public private. But why?
The idea is to prohibit the creation of instances of the object S in the aftermath by making it a singleton.
I came up with a hook, but it works as long as there is compatibility (as I understand it):
class S extends T{
  private function S(){
    // код
  }
}

Then everything rolls and it’s impossible to do something like that
$s = new S();
.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
Timofey, 2015-09-12
@mr_T

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.

M
matperez, 2015-09-12
@matperez

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 question

Ask a Question

731 491 924 answers to any question