不使用参数值的函数

Function not using arguments values

我正在尝试重用一个函数,但它没有获取参数值:

function has_children($arg1, $arg2){
    echo $arg1.'<br>'.$arg2;
    $children = get_term_children( $arg1, 'area' );
    if(empty($children)){
        $term_children_slug = $arg2;
    }
}

使用的地方之一

if (is_tax('area')){
    $term_slug = $queried_object->slug;
    $term_id = $queried_object->term_id;
    has_children($term_id, $term_slug);
}

这些值被打印但没有在函数内部使用。

你的意思是:

function has_children($arg1, $arg2){
    echo $arg1.'<br>'.$arg2; // args printed here
    $children = get_term_children( $arg1, 'area' ); // not used here?
    if(empty($children)){
        $term_children_slug = $arg2;
    }
}

你怎么知道它们没有在函数中使用?你希望发生什么?

$term_children_slug 在函数范围内未声明为全局时,您无法访问它。

function has_children($arg1, $arg2){
    /* Return type 1 */
    $term_children_slug = '';

    echo $arg1.'<br>'.$arg2; // args printed here
    $children = get_term_children( $arg1, 'area' ); // not used here?
    if(empty($children)){
        $term_children_slug = $arg2;
    }
    /* Return type 2-Remove Comments and return type 1
    return (isset($term_children_slug)) ? $term_children_slug : '';
    */

    /* Return type 1 */
    return $term_children_slug;
}
if (is_tax('area')){
    $term_slug = $queried_object->slug;
    $term_id = $queried_object->term_id;
    /* If you want to get result */
    $result = has_children($term_id, $term_slug);
}

有关详细信息,请查看 didierc 答案

问题

就目前而言,您的函数没有明显的副作用:它调用了一个用途未知的函数,并修改了一个未声明为全局变量或由该函数返回的变量。

可能的修复

在函数范围内导入全局:

function has_children($arg1, $arg2) {
  global $term_children_slug;
  echo $arg1.'<br>'.$arg2;
  $children = get_term_children( $arg1, 'area' );
  if(empty($children)){
    $term_children_slug = $arg2;
  }
}

Return计算值:

function has_children($arg1, $arg2) {
  $term_children_slug = 'default values';
  echo $arg1.'<br>'.$arg2;
  $children = get_term_children( $arg1, 'area' );
  if(empty($children)){
    $term_children_slug = $arg2;
  }
  return $term_children_slug;
}

不要忘记用默认值初始化变量(可以是 $children 中的值)。