2016-06-10 99 views
0

我正在處理一個應用程序,並且遇到了這種困境。下面是一個非常簡化的版本,但我想知道,如果可能的訪問已被父類方法修改的子類中的屬性

例子:

class A{ 

    public $test = null; 

    public function method1(){ 
     $this->test = 'finished'; 
    } 
} 

class B extends A{ 

    public function getMethod1Test(){ 
     return $this->test; 
    } 
} 

$a = new A(); 
$a->method1(); 

$b = new B(); 
$b->getMethod1Test(); //this currently returns NULL 

我怎麼能修改此使得其返回值「完成」,而不重新插入修改後的值到B級?

感謝

+3

$ b是一個不同的對象。您需要在$ b-> getMethod1Test()之前調用$ b-> method1() –

+0

問題不在於不同的類,它與不同的對象有關。每個對象都有自己的屬性變量副本,除非你聲明它是'static'。 – Barmar

+0

從'B'調用'method1()'? – AbraCadaver

回答

0

如果創建A級這樣的..

class A{ 
    public $test = null; 
    public function __construct(){ // constructor 
      $this->test = 'finished'; 
     } 
} 

我沒有測試它雖然,但應該工作。