2017-02-04 124 views
0

假設我有兩個類A和同一個變量B.修改父類變量

class A { 
    public $status; 
    public function __construct(){} 
} 

class B extends A { 
    public $status; 
    public function __construct(){} 

public function modifyParentStatus(){ 
    /* In the next line i want to change the parent class variable 
    But it changes the current class variable */ 
    $this->status = 'active'; 
} 
} 

$obj = new B(); 
$obj->modifyParentStatus(); 

如何更改父變量從子類,如果兩個變量具有相同的名稱?

我不想使用額外的靜態函數。我只是想直接修改它。

+0

有類無父變量'B' –

+0

什麼你的意思是?父類和子類中有相同的變量。我想更改子類中的父類變量。 –

+0

有沒有一個實際的用例在這裏代碼示例哪裏沒有做你期望的?你如何引用類變量,我沒有看到任何地方? –

回答

0

它沒有任何意義。沒有父母財產,這不是如何繼承的作品。

對象B($obj)沒有「父級」,類B沒有,但是這些是實例屬性。

如果您在子類中定義了一個附加屬性,那麼該類的一個實例將有權訪問這兩個屬性(在父級中定義的屬性以及在cild中定義的屬性)。但既不屬於「父母」班,你在這方面的事情就混淆了;就實例而言,所有這些屬性都是「本地」的。

你的modifyParentStatus()只是名字不好,因爲我認爲你不完全理解發生了什麼。

通過繼承類,它繼承了它的所有屬性。該類可能有一個父類,但該實例沒有。即使是static屬性,如果在子類中進行了重新定義,也不會創建新的可訪問屬性。 parent::$status,self::$status,static::$status將引用相同的屬性。

-1

你可能正在尋找到從子類的對象改變父類的一個對象的屬性,這將是實現這種方式

class A { 
     public $status; 
     public function __construct(){} 
     } 

class B extends A { 
     public $status; 
     public function __construct(){} 

     public function modifyParentStatus(){ 
     /* In the next line i want to change the parent class variable 
     But it changes the current class variable */ 
     //you need to create an instance of the parent class for you to access its properties 
     $a = new A(); 
     $a->status = 'active'; 
     return $a->status; 
    } 
} 

$obj = new B(); 
echo $obj->modifyParentStatus();