简体   繁体   English

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

[英]How to get Parent class variable value in child class construct method

I have two files:我有两个文件:

ParentClass.php 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;

?>

And ChildClass.php和 ChildClass.php

<?php

include "ParentClass.php";

class ChildClass extends ParentClass {

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

$obj = new ChildClass;

?>

When I run the ChildClass file in browser, it gives me the the value of only variable 2. It does not show the value of variable1.当我在浏览器中运行 ChildClass 文件时,它只给了我变量 2 的值。它没有显示变量 1 的值。 I need to print both variable1 and variable2 values.我需要打印 variable1 和 variable2 值。 Please Help.请帮忙。

you need to call parent::__construct() in your child contruct你需要在你的子结构中调用 parent::__construct()

the working code should be:工作代码应该是:

ParentClass.php 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;

?>

And ChildClass.php和 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;

?>

TRY this and see if it works:)试试这个,看看它是否有效:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM