簡而言之:一個類從父類繼承了一個函數。然後該函數被調用,但似乎仍然具有父類類的範圍。這是預期的行爲?奇怪的PHP的oop行爲,有人可以解釋嗎?
考慮下面的代碼示例:
<?php
class OLTest {
private $var1 = 10;
public function getVar1() {
if (isset($this->var1)) {
return $this->var1;
} else {
return 'undefined';
}
}
public function getVar2() {
if (isset($this->var2)) {
return $this->var2;
} else {
return 'undefined';
}
}
}
class OLTest2 extends OLTest {
private $var1 = 11;
private $var2 = 20;
}
$oltest = new OLTest();
$oltest2 = new OLTest2();
echo "calling parent->getVar1\n";
echo $oltest->getVar1() . "\n";
echo "calling parent->getVar2\n";
echo $oltest->getVar2() . "\n";
echo "calling child->getVar1\n";
echo $oltest2->getVar1() . "\n";
echo "calling child->getVar2\n";
echo $oltest2->getVar2() . "\n";
?>
據我瞭解,輸出應該是:
calling parent->getVar1
10
calling parent->getVar2
undefined
calling child->getVar1
11
calling child->getVar2
20
我的機器上的實際輸出爲
calling parent->getVar1
10
calling parent->getVar2
undefined
calling child->getVar1
10
calling child->getVar2
undefined
要添加在這兩個函數中的一個print_r($this)
混淆,將顯示範圍我實際上設置爲子類,但是不可能訪問變量。
有人可以幫我解決這個問題嗎?
編輯:我在版本5.3.3-1ubuntu9.5中使用PHP。
哪個版本的PHP? – 2011-05-27 14:35:17
忘了這一點。其5.3.3。 – 2011-05-27 14:37:20
添加爲檢查isset和返回值或未定義的簡單方法 – 2011-05-27 14:52:13