如何在子类构造方法中获取父类变量值

我有两个文件:

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值。请帮忙。

kaigewang 回答:如何在子类构造方法中获取父类变量值

您需要在子结构中调用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;

?>

尝试一下,看看是否有效:)

本文链接:https://www.f2er.com/3156179.html

大家都在问