You've hinted http://php.net/manual/en/language.oop5.typehinting.phpPHP 需要一个实例FetchMode
(就像错误消息中所说的那样),但是FetchMode::FETCH*
传递常数value。你必须使用某种 Enum 实例(我们在 PHP 中本身没有这种实例。(哦,好吧,有SplEnum
但谁使用它?))或更改方法签名以排除类型提示。
但是,您可以代替开关/外壳通过多态性更容易解决这个问题 http://sourcemaking.com/refactoring/replace-conditional-with-polymorphism and a 策略模式 http://sourcemaking.com/design_patterns/strategy,例如而不是做类似的事情
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:
}
}
这将增加圈复杂度 https://en.wikipedia.org/wiki/Cyclomatic_complexity您的班级并强制更改该班级以及FetchMode
每当你需要添加额外的 FetchModes 时,你可以这样做:
public function getRecordSet(FetchMode $fetchModeStrategy)
{
return $fetchModeStrategy->fetch();
}
然后有一个界面 http://php.net/manual/en/language.oop5.interfaces.php to 保护变异 http://martinfowler.com/ieeeSoftware/protectedVariation.pdf
interface FetchMode
{
public function fetch();
}
并添加混凝土FetchMode
每个受支持的 FetchMode 的类
class FetchOne implements FetchMode
{
public function fetch()
{
// code to fetchOne
}
}
class FetchAll …
class FetchRow …
这样,您就永远不必用它来接触班级getRecordSet
再次方法,因为它适用于任何实现该方法的类FetchMode
界面。因此,每当您有新的 FetchModes 时,您只需添加一个新类,从长远来看,它更易于维护。