如何在php函数中使用常量作为参数定义?
|
我有一节课: class FetchMode
{
const FetchAll = 0;
const FetchOne = 1;
const FetchRow = 2;}
和功能: function getRecordSet(FetchMode $FetchMode){ some switch cases }
我想使用$FetchMode作为切换案例标准,但收到错误: 这就是我调用函数的方式: getRecordSet(FetchMode::FetchOne); 我想提供一个调用函数的可能选择列表. 但是,您可以使用solve this more easily via Polymorphism和Strategy pattern代替Switch / Case.而不是做类似的事情 public function getRecordSet($mode)
{
switch ($mode) {
case FetchMode::ALL:
// code to do a fetchAll
break;
case FetchMode::ONE:
// code to do a fetchOne
break;
default:
}
}
这将增加你的类的Cylcomatic Complexity并强制更改到该类和FetchMode,只要你需要添加额外的FetchModes,你可以这样做: public function getRecordSet(FetchMode $fetchModeStrategy)
{
return $fetchModeStrategy->fetch();
}
然后有一个interface到protect the variation interface FetchMode
{
public function fetch();
}
并为每个支持的FetchMode添加具体的FetchMode类 class FetchOne implements FetchMode
{
public function fetch()
{
// code to fetchOne
}
}
class FetchAll …
class FetchRow …
这样,您将永远不必再次使用该getRecordSet方法触及该类,因为它适用于实现该FetchMode接口的任何类.因此,无论何时有新的FetchModes,您只需添加一个新类,从长远来看,它更易于维护. (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
