首页 > 解决方案 > 检查空函数参数的更好方法

问题描述

几乎我所有的类方法都以相同的方式开始,通过检查传递的参数是否为空(我期望 bool 和 int-0 的变化)

是否有一种较少重复的检查值的方法?

public function updateproduct($product, $storeid) {
    if ( empty($product) || empty($storeid) ) {
        return false;
    }

    // do stuff

}

标签: phpfunctionmethodsis-empty

解决方案


此函数测试是否有任何传递给它的参数为空。优点是简单。缺点是如果找到空值,它不会短路。

我想如果你注意到它的影响不是短路,你会向你的函数发送太多参数。

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;
  }

推荐阅读