2016-06-10 106 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'; 
     } 
} 

我没有测试它虽然,但应该工作。