簡體   English   中英

如何在子 class 構造方法中獲取父 class 變量值

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

我有兩個文件:

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 值。 請幫忙。

你需要在你的子結構中調用 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;

?>

試試這個,看看它是否有效:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM