I
I
Ivan Ivanov2019-06-29 00:09:19
PHP
Ivan Ivanov, 2019-06-29 00:09:19

How to create a constructor in an extendable class?

Hello!
1. In the router
$cObj = new $controller(self::$route);
2. Base controller

<?php


namespace vendor\core\base;


abstract class Controller
{
    public $route = [];

    public function __construct($route)
    {
        $this->route = $route;
    }
}

3. Application controller
<?php


namespace app\controllers;


use vendor\core\base\Controller;

class AppController extends Controller
{
    public $test = [];
}

4. Some (any) controller
<?php


namespace app\controllers;


class MainController extends AppController
{
    public function indexAction()
    {
        $this->test['a'] = 1;
        $test = $this->test; // собираем всё вместе
    }
}

How to create a constructor in an application controller? This is necessary so that all controllers have common functionality, you need to put in this constructor, for example, this code Thank you.
$this->test['b'] = 2;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
bkosun, 2019-06-29
@Artsiom_Ryzhanki

Constructors defined in parent classes are not automatically called if the child class defines its own constructor. To call a constructor declared in a parent class, call parent::__construct() inside the constructor of the child class. If a constructor is not defined in the child class, then it can be inherited from the parent class as a normal method (if it has not been defined as private).

Simple example:
class BaseClass {
   function __construct() {
       print "Конструктор класса BaseClass\n";
   }
}

class SubClass extends BaseClass {
   function __construct() {
       parent::__construct();
       print "Конструктор класса SubClass\n";
   }
}

https://www.php.net/manual/en/language.oop5.decon.php

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question