php - 如何在 Laravel Controller 中使用方法重载?

标签 php laravel oop overloading

我正在尝试在我的 Laravel Controller 类中使用方法重载功能。这是我的方法

  # 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', 'CustomerController@createBalance');

    Route::get('Customer/Balance/{ID}', 'CustomerController@createBalance');

但它显示错误-

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

有什么解决办法吗?

最佳答案

考虑使用默认参数:

  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?}', 'CustomerController@createBalance');

在参数后添加一个 "?",Laravel 知道您正在传递一个可选参数。

关于php - 如何在 Laravel Controller 中使用方法重载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43786355/

相关文章:

javascript - 在您最好从数据库/Excel 中选择第一个列表中的元素后,如何填充第二个列表

php - 使用 JSON 发送二进制文件内容

.net - 添加扩展方法我觉得应该在框架: bad idea?

javascript - Google Maps API imagePath 本地镜像无法正常工作

mysql - 如何使用 Eloquent 在 Laravel 中设置 AUTO_INCREMENT?

php - Laravel 5.2 如何在同一行显示成员列表和他/她的组(一对多(或多对多)数据显示)

php - Laravel 验证 zip 文件内容

ios - Swift 变量应该在哪里声明

php - 将 PHP 对象发送到另一个 PHP 页面

javascript - 如何从 php 或 node.js 获取 websocket url 路径