D
D
Dmitry2016-02-20 00:03:13
PHP
Dmitry, 2016-02-20 00:03:13

Do I need to call the constructor of the inherited class?

Hello.
Here is an example that raised doubts about my actions:

abstract class A extends PDO{
    public function __construct(){
        // устанавливаем соединение с бд
    }
...
}
class B extends A{
    function __construct(){
        parent::__construct();
    }
// используем методы из A

}

The bottom line is that if you do not use such a constructor in class B, then an error pops up:
Call to a member function prepare() on null in

According to the idea of ​​abstract classes - they cannot be initialized. That's what I need. But I would like that when inheriting such an abstract class, a function of the constructor type is launched, without calling the constructor in the child class, as in my example. Is it possible?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
D
D', 2016-02-20
@Denormalization

It is possible through reflection, it is possible through magical methods. But IMHO this is a shitty way, since such a "magical" behavior entails errors in the future.
It is better to CLEARLY call all the necessary methods, not forgetting to register this method in the interface, then there will certainly be no problems.

Y
Yuri, 2016-02-20
@riky

But I would like that when inheriting such an abstract class, a function of the constructor type is launched, without calling the constructor in the child class, as in my example. Is it possible?

if you get confused, you can, but this is an anti-pattern. requiring that the child constructor must call the parent is the norm.
any adequate developer of the final logic is obliged to look at the constructors and figure it out, or he will initiate everything himself or simply call the parent. especially since the parent can also accept parameters.

D
Dmitry, 2016-02-20
@kiff86

Can the __counstract method be abstract? Because in an abstract class, an abstract method enforces a mandatory declaration in the child class.

P
profesor08, 2016-02-20
@profesor08

If you need a constructor to call the parent's constructor, then you don't need a constructor, and you can remove it from the class. And then, when creating an object of the heir class, the default constructor will be called, that is, the constructor of the parent, or great-parent, or great-great-great...

abstract class A extends PDO{
    public function __construct(){
        // устанавливаем соединение с бд
    }
...
}
class B extends A{

}

$o = new B();
$o->query("drop database master");

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question