你有
hinted PHP期待一个FetchMode实例(就像它在错误消息中所说的那样),但是FetchMode :: FETCH *传递常量值.你必须使用某种Enum实例(我们在PHP中没有本地实例.(哦,有SplEnum,但谁使用它?))或更改方法签名以排除typehint.
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 FetchMode
{
public function fetch();
}
并为每个支持的FetchMode添加具体的FetchMode类
class FetchOne implements FetchMode
{
public function fetch()
{
// code to fetchOne
}
}
class FetchAll …
class FetchRow …
这样,您将永远不必再次使用该getRecordSet方法触及该类,因为它适用于实现该FetchMode接口的任何类.因此,无论何时有新的FetchModes,您只需添加一个新类,从长远来看,它更易于维护.