簡體   English   中英

PHP Access公共變量從子類收縮

[英]PHP Access public variable changed in constrict from child class

如何訪問父類使用__construct設置的子類中的公共屬性?

例如:

class Parent
{
    protected $pVariableParent = 'no info'; //This have to be set for all classes

    public function __construct()
    {
        $this->setPVariable(); //Changing the property when class created.
    }

    public function setPVariable(){
        $this->pVariableParent = '123';
    }
}

Class Child extends Parent
{
    public function __construct()
    {
        if(isset($_GET['info']){
            echo $this->pVariableParent;
        }
    }
}

$pInit = new Parent;
$cInit = new Child;

在這種狀態下,請求site.php/?info顯示no info 但是如果我調用$this->setPVariable(); 來自Child,一切正常,並顯示123 為什么我無法從父級訪問已更改的屬性? 是因為當我調用Child類時,它只讀取所有父級的屬性和方法,但不觸發任何構造函數嗎? 最好的方法是什么? 感謝名單。

問題是您覆蓋了父構造函數,因此在子構造函數中未調用setPVariable

擴展父構造函數而不是重寫:

Class Child extends Parent
{
  public function __construct()
    {
      parent::__construct();
      if(isset($_GET['info']){
        echo $this->pVariableParent;
    }
  }
}

http://php.net/manual/it/keyword.parent.php

讓我嘗試澄清一點:

為什么我無法從父級訪問已更改的屬性?

因為該屬性尚未更改。 您正在創建兩個單獨的對象; $pInit是父類的實例,其屬性值在構造函數中更改。 $cInit是子類的實例,並且其屬性值未更改,因為您覆蓋了構造函數,並且子類不更改屬性值。 $pInit$cInit不相關(按類型除外),它們當然不會相互影響。

暫無
暫無

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

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