【问题标题】:php method argument as enum/constphp 方法参数为 enum/const
【发布时间】:2012-05-14 11:58:43
【问题描述】:

有没有办法允许 enum 或 const 作为 PHP 中的方法参数。在 Qt/C++ 中,您可以像这样使用它,但 C++ 当然支持(取决于语言)。

Qt/C++/SslSocket

enum PeerVerifyMode {
    VerifyNone,
    QueryPeer,
    VerifyPeer,
    AutoVerifyPeer
};

void setPeerVerifyMode(QSslSocket::PeerVerifyMode mode);

我 PHP 我试过这个:

第一:

class Controller_My
{
  const MENU_FRONT   = 0;
  const MENU_SESSION = 1;

  public function render($menu_model)
  {
    $menu_model = intval($menu_model);

    if( $menu_model === 0 )
      $menu = new Model_Menu_Front();

    if( $menu_model === 1 )
      $menu = new Model_Menu_Session();
  }
}

我也读过这篇文章how to use constant from class as an argument definition in php function?。但即使使用http://sourcemaking.com/refactoring/replace-conditional-with-polymorphism interface/implements 解决方案,如果您偏执,您也可以使用 switch/if 语句。像这样:

class EmployeeType...
  int payAmount(Employee emp) {
    switch (getTypeCode()) {
        case ENGINEER:
           return emp.getMonthlySalary();
        case SALESMAN:
           return emp.getMonthlySalary() + emp.getCommission();
        case MANAGER:
           return emp.getMonthlySalary() + emp.getBonus();
        default:
           throw new RuntimeException("Incorrect Employee");
    }
}

【问题讨论】:

    标签: php enums constants


    【解决方案1】:

    SplEnum 和用户注释为例。

    【讨论】:

    • 为什么不提供正确的示例代码? “用户注释”不是静态的,也不是特定的。
    猜你喜欢
    • 1970-01-01
    • 2021-01-09
    • 1970-01-01
    • 1970-01-01
    • 2011-05-08
    • 2012-07-22
    • 2012-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多