簡體   English   中英

如何從子類訪問父變量

[英]how to access parent variable from child class

我有兩個類,一個父類,另一個擴展,我需要在擴展類中使用主變量。 例如

class parentClass
{
    $this->value = null
    function __construct()
    {
        echo "im parent" ;
    }

}
class childClass extends parentClass
{

    function sayIt()
    {
        var_dump($this->value);
    }
}

$p = new parentClass ; 
$p->value = 500 ; 

$c = new childClass ; 
$c->sayIt(); // this output null ! i want it to output 500 , how i can do that

謝謝

這不是繼承的方式。 childClass不會自動連接到父類,它只是從parentClass繼承而來,它只是從父類繼承所有公共和受保護的變量/方法。 它未連接到父實例。

如果將其擁有以輸出500,則必須以某種方式將其分配給子類實例:

$c = new childClass ; 
$c->value = 500;
$c->sayIt()

如果需要在所有類和實例之間共享的變量,則可以使用static變量。

Bad Bad Bad該代碼嚴格用於教育目的,我建議您獲得有關面向對象編程的基本原理的書

將變量設為靜態將使其可通過子類訪問

class parentClass {
    public static $value = null;

    function __construct() {
        echo "patent called";
    }
}
class childClass extends parentClass {

    function sayIt() {
        var_dump(self::$value);
    }
}

$p = new parentClass();
parentClass::$value = 500;

$c = new childClass();
$c->sayIt();

您會混淆類構造和引用。

$p是父類的實例。

$c是子類的實例。

他們不共享數據。

暫無
暫無

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

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