2012-08-01 176 views
3

这是我的第一个问题,并且让我难住。我不确定这是否简单,我忽略它或某些不可能的事情。PHP5 OOP:访问更改的父属性

下面是我的原始代码的一个非常简化的版本。最终的目标是让输出如下:

1: 
2: this is a test 
3: this is another test 
4: this is another test 

然而,在当前状态下的代码,它的实际输出是这样的:

1: 
2: this is a test 
3: this is another test 
4: 

我想对象“B”,能够访问test_variable的值后,first_function()已经改变它。

当我将test_variable声明为静态时它工作正常,但是在实际的应用程序中它不起作用,当我试图回显parent :: test_variable时,它输出'Object ID#17'等等。

class A 
{ 
    public $test_variable; 

    function __construct() 
    { 
     echo '1: ' . $this->test_variable . "<br />"; 
     $this->test_variable = 'this is a test'; 
     echo '2: ' . $this->test_variable . "<br />"; 
    } 

    function first_function() 
    { 
     $this->test_variable = 'This is another test'; 
     echo '3: ' . $this->test_variable . "<br />"; 
     $b = new b; 
     $b->second_function(); 
    } 
} 



class B extends A 
{ 
    function __construct() 
    { 
     /* Dont call parent construct */ 
    } 

    function second_function() 
    { 
     echo '4: ' . $this->test_variable; 
    } 
} 

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

// Outputs: 
// 1: 
// 2: this is a test 
// 3: this is another test 
// 4: 

// but I want it to output 
// 1: 
// 2: this is a test 
// 3: this is another test 
// 4: this is another test 

非常感谢您的回复。我非常感谢他们。

菲尔

回答

2

声明public $test_variable;里面的类是指类的每个实例(对象)有一个副本。类A中的$test_variable未指向与B类中的$test_variable相同的内存地址。这是有意完成的,以允许范围并移除全局状态。正如你之前所说,声明它静态将工作,因为然后每个实例共享相同的变量。

在这种情况下,$test_variable本质上是类B所需的依赖关系。你可以通过构造函数注入这种依赖性很容易:

class A 
{ 
    public $test_variable; 

    function __construct() 
    { 
     echo '1: ' . $this->test_variable . "<br />"; 
     $this->test_variable = 'this is a test'; 
     echo '2: ' . $this->test_variable . "<br />"; 
    } 

    function first_function() 
    { 
     $this->test_variable = 'This is another test'; 
     echo '3: ' . $this->test_variable . "<br />"; 

     // Instantiate instance passing dependency 
     $b = new b($this->test_variable); 

     $b->second_function(); 
    } 
} 

class B extends A 
{ 
    function __construct($dependency) 
    { 
     // Set dependency 
     $this->test_variable = $dependency; 
    } 

    function second_function() 
    { 
     echo '4: ' . $this->test_variable; 
    } 
} 

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

所以,这只是你会如何考虑处理这一个念头。

+0

嗨Cillosis非常感谢您的回答,这是非常有益的。我之前已经考虑过这种方法,并且我认为它可能是我期望的最好的方法,但是我非常欣赏这种解释,理解问题并获得答案总是有帮助的! – user1569083 2012-08-01 19:36:32