這是我的第一個問題,並且讓我難住。我不確定這是否簡單,我忽略它或某些不可能的事情。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
非常感謝您的回覆。我非常感謝他們。
菲爾
嗨Cillosis非常感謝您的回答,這是非常有益的。我之前已經考慮過這種方法,並且我認爲它可能是我期望的最好的方法,但是我非常欣賞這種解釋,理解問題並獲得答案總是有幫助的! – user1569083 2012-08-01 19:36:32