有时候,您可能需要根据某个变量的值调用不同的函数。就像这样:
if ($var == 'someValue1') {
$someObj->abc();
} elseif ...
} elseif ($var == 'someValueN') {
$someObj->xyz();
}
在PHP中实现这个任务有许多方法,我找到了8种可能的选项:
- 使用一堆if/else语句
- 使用switch语句
- 使用可变函数
- 使用匿名函数(定义一个匿名函数数组)
- 使用call_user_func和call_user_func_array函数
- 使用多态:抽象基类+一堆子类
- 使用eval语句
- 使用ReflectionMethod::invoke方法
附言: 以下是一个可能需要根据变量值调用不同方法的示例:
/**
* Checks if all needed parameters are present in the HTTP request
* @param array $params Parameters which have to be present in the request
* @throws MissingParameterException if any of the given parameters is missing
*/
public function checkParametersExistence($params)
{
foreach ($params as $param) {
$method = $param[0]; // a type of the param: get, post, put, delete
$name = $param[1]; // a name of the param
$code = $param[2]; // a code to send if this param is missing
// $exists = $this->request->isGetParamSet($name);
// ... = $this->request->isPostParamSet($name);
// ... = $this->request->isPutParamSet($name);
// ... = $this->request->isDeleteParamSet($name);
if ($exists == false) {
throw new MissingParameterException($name, $code);
}
}
}
if / else
,如果它们失败了就让它们抛出异常。然后你只需要在一个验证方法中拥有一个验证器列表,这似乎足够整洁和可读。 - halfer/SausageSearch/:meatType
会指定这个端点需要一个必需的肉类类型字符串。如果你想了解更多关于这方面的内容,可以查看Slim或Silex的路由部分 - 它们通常有语法来使参数可选,应用正则表达式条件等。通常,如果这些验证失败,路由会被忽略,这通常是所需的。当然,你也可以在路由器中更加宽容,然后在处理程序中引发错误,如果你愿意的话。 - halfer