作者htl74421 (<><魚仔<>< 薰~)
看板PHP
標題[請益] class繼承問題
時間Thu Jul 11 16:00:05 2013
我目前的疑惑是這樣:
class grandfather { //祖父
public function grandfather()
{
//
}
public function get_data()
{
echo 'hello';
}
}
class father extends grandfather { //爸爸
public function father()
{
//
}
}
class child extends father{ //小孩
public function child()
{
//
}
public function test()
{
parent::get_data();
}
}
$a = new child();
$a->test();
我在 child 的 test() 中呼叫 father 的 get_data(), 但 father 沒有,所以我想應該
會跳錯誤出來,可是它的結果卻是再往上去找到 grandfather 的 get_data(),所以是採用
無限上綱的方式? 往上一直找到有為止?
這個樣子的話那如果中間是繼承了好幾層然後又有人去覆寫,這樣不就會造成我想的
get_data()不見得一定就是我想的那個,可能中間有人做了其它修改,這樣不就會大亂了嗎?
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 202.39.133.25
→ microtech:先理解"繼承"是什麼意思,哪來的無限上綱@@ 07/11 16:09
→ microtech:調用函式前指名正確的類別不就不會有問題了? 怎麼亂法? 07/11 16:10
→ dlikeayu:你每一層沒去return parent::function() 就只會找被 07/11 16:21
→ dlikeayu:覆蓋的 07/11 16:22
→ tkdmaf:說往上找是不對的。簡單來說……這叫遺傳........ 07/11 23:27
推 see7di:很簡單啊,用final來修飾就好了,這樣就不會被重寫了 07/15 21:35