[英]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
謝謝
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.