2010-02-17 186 views
12

財產請看下面的例子(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和我有點懵。

在這裏訪問的父母屬性我使用的是一個類的實例,這似乎是錯誤的:S(不需要是我的孩子然後)。有沒有簡單的方法,以便我可以將父屬性與子屬性同步,並且可以直接訪問$ this-> anotherP而不必使用$ this-> parent-> anotherP?

回答

27

當你的Child類擴展您的Parent類,每一個屬性和方法要麼publicprotectedParent類將由Child類被看作是,如果他們在Child類中定義 - 和其他方式以防萬一。

ChildextendsParent類,它可以被看作是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 

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


爲了使事情變得簡單:作爲Child「是」 MyParent,它並不需要保持一個指向...本身;-)

+1

是的。對父:: ::構造的調用是我需要的:O – shxfee

+0

噢,是的,這是棘手的事情之一,我不想提及它:如果你的子類定義了一個構造函數,PHP將不會調用構造函數的父類 - 這意味着你必須自己調用它*(請參閱http://fr.php.net/manual/en/language.oop5.decon.php上的註釋)* –

-2

這應該工作..

class Child extends Parent 
{ 
    private function myMethod() 
    { 
    return $this->_anotherP; 
    } 
} 

因爲_anotherP它受保護,所以每個派生類都可以訪問它,但它不在另一個對象中,它是同一個對象。

但是,讓父母的獲得者是一個明智的選擇。

0

這可以爲您節省幾個小時的搜索周圍。

請記住:您的Child類只繼承父類中的DEFINED屬性...所以,如果你使用父類實例化一個對象,然後用數據填充它,那麼這些數據將不會在你的子類中提供...

這當然是非常明顯的,但我猜別人可能碰到同樣的問題。

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

class child { 

    public parentObject; 

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

} 

如果你的$ parentObject具有公共屬性$名字,那麼你就可以訪問它的孩子裏面類似功能:

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