2017-05-04 62 views
1

我想在我的laravel控制器類中使用方法重載功能。這裏是我的方法如何在Laravel控制器中使用方法重載?

# Load Customer Balance View 
    public function createBalance() 
    { 
    return view('customer.balance'); 
    } 

    # Load Customer Balance View 
    public function createBalance($CustomerID) 
    { 
    // show balance of the the defined customer 
    } 

這裏是我的路線 -

// customer balance 
    Route::get('Customer/Balance', '[email protected]'); 

    Route::get('Customer/Balance/{ID}', '[email protected]'); 

但它顯示的錯誤 -

FatalErrorException in CustomerController.php line 45: 
Cannot redeclare App\Http\Controllers\CustomerController::createBalance() 

任何解決辦法嗎?

+2

你不能。 PHP不是以這種方式構建的。 – aynber

+1

https://softwareengineering.stackexchange.com/questions/165467/why-php-doesnt-support-function-overloading – aynber

+0

是不是php OOP語言?它具有OOP語言的功能,具有方法重載功能。 –

回答

3

考慮使用默認參數:

public function createBalance($CustomerID=null) 
    { 
    if ($CustomerID==null) 
     return view('customer.balance'); 
    else 
     // show balance of the the defined customer 
    } 

,改變你的路線: 「?」

Route::get('Customer/Balance/{CustomerID?}', '[email protected]'); 

添加之後,Laravel理解你正在傳遞一個可選參數。

+1

謝謝路易斯:)。儘管我已經完成了計算函數參數的任務,但我必須編寫兩個路由調用。跟着你,它爲我節省了一條線。 –

1

您需要有不同的方法名稱。這也不遵循基本的路由約定。第一個createBalance方法應該可能是索引方法。

1

我認爲createBalance()方法alredy存在於你的CustomerController,所以你應該創建新的方法或不同的名稱方法,並在新的方法名稱更改路由文件。

相關問題