php - 检查空函数参数的更好方法
问题描述
几乎我所有的类方法都以相同的方式开始,通过检查传递的参数是否为空(我期望 bool 和 int-0 的变化)
是否有一种较少重复的检查值的方法?
public function updateproduct($product, $storeid) {
if ( empty($product) || empty($storeid) ) {
return false;
}
// do stuff
}
解决方案
此函数测试是否有任何传递给它的参数为空。优点是简单。缺点是如果找到空值,它不会短路。
我想如果你注意到它的影响不是短路,你会向你的函数发送太多参数。
function anyEmpty(...$args){
return array_filter($args) !== $args;
}
然后我们在 updateProduct 函数中的用法:
function updateProduct($product, $storeId){
if (anyEmpty($product, $storeId)) {
return False;
}
//do your stuff
return True;
}
或者,如果您希望动态指定参数:
if (anyEmpty(...func_get_args())) {
return False;
}
推荐阅读
- xslt - 如何在if条件中附加字符串值
- javascript - 在异步 Axios POST 后从服务器检索消息
- behat - 使用 @javascript 进行的测试在 Sylius 中不起作用(插件)
- react-functional-component - REACT 动态导航栏突出显示当前部分
- sql - 为什么 != 运算符比 = 运算符快?
- python - 解包问题:解包需要 31 个字节的缓冲区
- r - 在每个组的分类 x 轴内覆盖 geom_line - ggplot2
- mongodb - mongodb复杂聚合嵌套条件groupby
- jib - Maven 找不到 JIB 插件?
- python - Django Framework - 如果值已经存在,如何让用户覆盖现有值