2017-05-30 57 views
0

我有一個方法:使用,其僅在子類中定義的方法

protected function chooseAndUpdateParentFight(Fight $fight, Fight $parentFight) 
{ 
    $fighterToUpdate = $fight->getParentFighterToUpdate(); 
    ... 
} 

我有2種戰鬥:PreliminaryFightDirectEliminationFight

兩者都是Fight

事情子類getParentFighterToUpdate()的定義只存在於兩個子類中,但不在Fight類中,所以我得到:

BadMethodCallException in Builder.php line 2443: 
Call to undefined method 
Illuminate\Database\Query\Builder::getParentFighterToUpdate() 

我該怎麼辦?

編輯:這裏都是getParentFighterToUpdate方法:

DirectEliminationFight類別:

public function getParentFighterToUpdate() 
{ 
    $childrenGroup = $this->group->parent->children; 
    foreach ($childrenGroup as $key => $children) { 
     $childFight = $children->fights->get(0); 
     if ($childFight->id == $this->id) { 
      if ($key % 2 == 0) { 
       return "c1"; 
      } 
      if ($key % 2 == 1) { 
       return "c2"; 
      } 
     } 
    } 
    return null; 
} 

PreliminaryFight類

public function getParentFighterToUpdate() 
{ 
    $childrenGroup = $this->group->parent->children; 
    foreach ($childrenGroup as $key => $children) { 
     $childFights = $children->fights; 
     dd($childFights); 
     // Still writing it 
    } 
    return null; 
} 

編輯2:

/** 
* Update fighter if it is possible 
* @param $fightsByRound 
*/ 
protected function updateParentFight(Collection $fightsByRound) 
{ 

    foreach ($fightsByRound as $fight) { 
     $parentGroup = $fight->group->parent; 
     if ($parentGroup == null) break; 
     $parentFight = $parentGroup->fights->get(0); 
     $this->chooseAndUpdateParentFight($fight, $parentFight); 
    } 
} 
+0

你可以同時顯示'getParentFighterToUpdate()'方法嗎? –

+0

我編輯了我的問題 –

+0

一個粗略的方法是在'Fight'模型中定義'getParentFighterToUpdate',然後就像這樣:'if(class_basename(static :: class)=='PreliminaryFight')'將它們分開向上。這就是說有沒有一個原因,你沒有將其中一個子類傳遞給'chooseAndUpdateParentFight'? –

回答

0

可以使用定義getParentFighterToUpdate方法的接口並讓Fight類實現它。

但是,實際的問題似乎是在別的地方,因爲你顯然將Illuminate\Database\Query\Builder的實例傳遞給你的方法,而不是Fight。檢查你的方法調用是否通過了正確的變量

+0

接口會聲明它但沒有定義它。另外,我不想讓Fight去實現它,只是子類。第二個問題不是問題,Fight是一個模型,但它會工作,如果我能解決這個問題 –

+0

由於PHP沒有靜態類型檢查,如果給定的對象有方法,那麼該方法調用應該工作,即使Fight不' t宣佈它。你可以嘗試一個get_class或var_dump傳遞參數,看看他們是否正確?您也可以嘗試刪除類型提示並查看是否有效 –

+0

我已經嘗試刪除該提示,但沒有成功。 get_class必須是Fight類型,因爲我強制輸入,你不同意嗎? –

相關問題