Answer the question
In order to leave comments, you need to log in
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;
}
}
<?php
namespace app\controllers;
use vendor\core\base\Controller;
class AppController extends Controller
{
public $test = [];
}
<?php
namespace app\controllers;
class MainController extends AppController
{
public function indexAction()
{
$this->test['a'] = 1;
$test = $this->test; // собираем всё вместе
}
}
$this->test['b'] = 2;
Answer the question
In order to leave comments, you need to log in
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).
class BaseClass {
function __construct() {
print "Конструктор класса BaseClass\n";
}
}
class SubClass extends BaseClass {
function __construct() {
parent::__construct();
print "Конструктор класса SubClass\n";
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question