2011-02-16 217 views
0

如何從類A中實例化的對象訪問類A的屬性。訪問類屬性

像這樣;

class A() 
public var1; 
public obj1; 

function __construct(){ 
    $this->var1 = 'Hello World'; 
    $this->obj1 = new B(); 
} 

==============

class B() 

function anything(){ 
    #i want to access var1 from the calling class here ???? 
    # how do i access var1 in the calling class 
} 
+0

*(參考)* [類和對象 - 基礎](http://de2.php.net/manual/en/language.oop5.basic.php) – Gordon 2011-02-16 08:59:01

+0

* (相關)* [學習OOP](http://stackoverflow.com/search?q=learning+oop+php) – Gordon 2011-02-16 08:59:41

回答

3

有這樣做的直接方式。依賴注入是一種可能性:

class B { 

    protected $A = null; 

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

    public function foo() { 
     $this->A->var1; 
    } 

} 

class A { 

    public function __construct() { 
     $this->obj1 = new B($this); 
    } 

}