簡體   English   中英

從孩子訪問父類的屬性

[英]Accessing Parent Class' property from child

請參見以下示例(PHP)

class Parent
{ 
  protected $_property;
  protected $_anotherP;

  public function __construct($var)
  {
    $this->_property = $var;
    $this->someMethod();  #Sets $_anotherP
  }

  protected function someMethod()
  ...
}

class Child extends Parent
{
  protected $parent;

  public function __construct($parent)
  {
    $this->parent = $parent;
  }

  private function myMethod()
  {
    return $this->parent->_anotherP;  #Note this line
  }
}

我是OOP的新手,有點無知。

在這里,我使用的是該類的實例來訪問parents屬性,這似乎是錯誤的:S(然后不需要成為i子代)。 有沒有一種簡單的方法,這樣我就可以將父屬性與子屬性同步並可以直接訪問$ this-> anotherP,而不必使用$ this-> parent-> anotherP?

當您的Child類擴展您的Parent類時, Child類將看到在Parent類中publicprotected所有屬性和方法,就像它們是在Child類中定義的一樣;反之亦然。

Childextends Parent類時,可以將其視為ChildParent -這意味着Child具有Parent的屬性,除非以其他方式重新定義了這些屬性。

(順便說一句,注意“ parent ”是PHP中的保留關鍵字,這意味着您不能使用該名稱來命名類)


這是“父”類的簡單示例:

class MyParent {
    protected $data;
    public function __construct() {
        $this->someMethodInTheParentClass();
    }
    protected function someMethodInTheParentClass() {
        $this->data = 123456;
    }
}

這是“孩子”類:

class Child extends MyParent {
    public function __construct() {
        parent::__construct();
    }
    public function getData() {
        return $this->data; // will return the $data property 
                            // that's defined in the MyParent class
    }
}

可以這樣使用:

$a = new Child();
var_dump($a->getData());

然后您將得到輸出:

int 123456

這意味着在MyParent類中定義並在相同MyParent類的方法中初始化的$data屬性可以由Child類訪問,就好像它是自己的一樣。


為了簡單MyParent :由於Child “是” MyParent ,它不需要保持指向...本身的指針;-)

這樣可以節省您幾個小時的搜索時間。

請記住:您的子類僅繼承父類中定義的屬性...因此,如果您使用父類實例化一個對象,然后用數據填充該對象,那么該數據將在您的子類中不可用...

這當然是非常明顯的,但是我猜想其他人可能會遇到同樣的問題。

一個超級簡單的解決方案是不擴展任何內容,只需通過構造函數將父類的$ object傳遞給子類。 這樣,您可以訪問父類生成的對象的所有屬性和方法

class child {

    public parentObject;

    public function __construct($parentObject) {
        $this->parentObject = $parentObject;
    }

}

如果您的$ parentObject具有公共屬性$ name,則可以使用以下函數在子類內部訪問它:

public function print_name() {
    echo $this->parentObject->name;
}

暫無
暫無

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

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