Как получить значение переменной родительского класса в методе конструирования дочернего класса - PullRequest
1 голос
/ 06 ноября 2019

У меня есть два файла:

ParentClass.php

<?php

class ParentClass {

    public $variable1;
    public $variable2 = "Value of variable 2";

    public function __construct()
    {
        $this->variable1 = "Value of variable 1";
    }
}

$obj = new ParentClass;

?>

И ChildClass.php

<?php

include "ParentClass.php";

class ChildClass extends ParentClass {

    public function __construct()
    {
            echo $this->variable1;
            echo $this->variable2;
    }
}

$obj = new ChildClass;

?>

Когда я запускаю файл ChildClass в браузере, он даетмне значение только переменной 2. Это не показывает значение переменной1. Мне нужно вывести значения variable1 и variable2. Пожалуйста, помогите.

1 Ответ

1 голос
/ 06 ноября 2019

вам нужно вызвать parent :: __ construct () в вашем дочернем конструкте

рабочий код должен быть:

ParentClass.php

<?php

class ParentClass {

    public $variable1;
    public $variable2 = "Value of variable 2";

    public function __construct()
    {
        $this->variable1 = "Value of variable 1";
    }
}

$obj = new ParentClass;

?>

и ChildClass. php

<?php

include "ParentClass.php";

class ChildClass extends ParentClass {

    public function __construct()
    {
            parent::__construct(); // like this
            echo $this->variable1;
            echo $this->variable2;
    }
}

$obj = new ChildClass;

?>

ПОПРОБУЙТЕ это и посмотрите, работает ли оно:)

...