A constructor call inside a method

Somehow my mind went far from the current problem, and I made a terrible mistake. I called the parent constructor inside the method, which simply initializes the properties of the classes .. Or I .. The parent constructor set the ID value. Well, PHP let me do this. But is that not so? And it looks like I can also call my own class constructor. Isn't it that constructors should only be allowed when instantiating a class ... And they are called only when instantiating.

<?php

    class A {

        public function __construct() {
            echo "Test<br />";
        }

    }

    class B extends A {

        public function test() {
            parent::__construct();
        }

    }

    $b = new B();
    $b->test();

    // OUTPUT:
    // Test
    // Test

?>

EDIT: So, the conclusion is that PHP allows you to call the constructor inside the method, but actually does nothing. And this other line "TEST" comes from the constructor of the base class.

+3
source share
4 answers

.

Override

, , __construct, , , parent.

:

class Parent
{
     public function start(){}
}
class Child extends Parent
{

}

start Child, Parent::Start(), Child Start(), Overriding .

-, php , , __construct() , PHP , , .

__construct Child, PHP __construct

2 x Test .

, parent:__cosntruct(), , , .

:

class Parent
{
     public function __construct()
     {
         //Do work on Parent Class
     }
}

class Child extends Parent
{
    public function __construct()
    {
         //Do Work on Child Class

         parent::__construct();
    }
}

, - , , , - , .

+3

. , .

php , , , , .

+1

This is not a good practice, and well-spoken OOP languages ​​usually do not allow you to do this. Although this is absolutely normal if you know exactly what you are doing. (And you can document that other programmers working with this code understand your concept).

0
source

I would suggest using the init method to handle this behavior. Here is an example:

class A {
    public function __construct() {
        $this->init();
    }
    protected function init() {
        echo "Test<br />";
    }
}

class B extends A {
    public function __construct() {
        // suppress parent constructor 
    }
    public function test() {
        $this->init();
    }
}
0
source

Source: https://habr.com/ru/post/1795871/


All Articles