2012-08-01 97 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