如果不是这样,或者只是在函数中返回一个值,那么什么是更好的,为什么


What is better if else or only if to return a value inside a function and why?

嗨,我犹豫要不要问这个问题,但我需要一些关于此示例代码的建议,以及下面两个函数之间更好的建议。

function get_product($productType){
  $product =[];
  if('available'== $productType){
    $product = array('tshirt','pants','polo'); 
  }else if('out_of_stock' == $productType){
    $product = array('short');
  }
  return $product;
}

function get_product($productType){
  $product = array('tshirt','pants','polo');
  if('out_of_stock' == $productType){
    $product = array('short');
  }
  return $product;
}

我只是想征求一些程序员的意见。提前谢谢。

我经常看到两者。如果它们在功能上都是相同的,并且没有性能/其他原因为什么你会选择一个特定的而不是另一个,那么选择最易读的一个,或者对你来说最有意义的一个。

但是,在这种特殊情况下,我可以指出,条件三元运算符会大大缩短时间:

function get_product($productType) {
    return 'out_of_stock' == $productType ?
            array('short') :
            array('tshirt','pants','polo');
}