变量函数名


Variable Function Names

我有以下列表…"ch"、"uk"answers"eu"……此列表将被动态添加到。

我需要创建一个循环,为列表中的每个项目创建函数。每个函数的内部代码都完全相同。(参见下面的完整函数示例)。唯一不同的是函数名。下面你会看到函数名是"filterthis_uk" -对于列表中的每一项,函数名应该是"filterthis_ch", "filterthis_eu"等等…

function filterthis_uk($form){
foreach( $form['fields'] as &$field ) {
$funcNameCode = substr(__FUNCTION__, strpos(__FUNCTION__, "_") + 1);
if ( false === strpos( $field['cssClass'], __FUNCTION__ ) || ! rgar( $field, 'allowsPrepopulate' ) )
continue;

$args = array( 'post_type' => 'product', 'posts_per_page' => -1, 'product_cat' => 'courses', 'meta_key' => 'course_start_date', 'meta_query' => array(
    array(
        'key'       => 'course_start_date',
        'compare'   => '>',
        'value'     => $today,
    ),
     array(
        'key'       => 'course_end_date',
        'compare'   => '>',
        'value'     => $today,
    ),
    array(
        'key'       => 'course_location',
        'value'     => $funcNameCode,
    )
),  'orderby' => 'meta_value_num', 'order' => 'ASC' );

$query = new WP_Query( $args );
$field['choices'] = array();
if ( empty( $query->posts ) ) {
// Empty field if needed
$field['choices'] = array( array( 'text' => 'No Courses Found', 'value' => '' ) );
}
else {
foreach( $query->posts as $post )
$field['choices'][] = array( 'text' => $post->post_title . $funcNameCode, 'value' => $post->ID );
}
// Add Other Choice
$field['enableOtherChoice'] = 1;
break;
}
return $form;
}

必须有一种方法可以做到这一点,使函数代码不需要重复。唯一改变的是函数名中"_"后面的两个字母。之后是列表中项目的值,即…"uk", "ch"等等

你应该把国家作为一个参数;

但是如果你觉得需要一个基于函数的API,为什么不创建一个类并使用__callstatic函数呢?这会更容易,更干净,而且不会挤占您的名称空间;

class filterCountry
{
  static $countries = ['uk', 'eu', 'ch'];
  static function __callstatic ($country, $args) 
  {
    if (in_array($country, self::$countries))
      /* logic. Note that $form will be under $args[0] */
    else
      /* graceful error handling */
  }
}

你的API看起来像…

filterCountry::uk($form);
filterCountry::eu($form);
filterCountry::ch($form);

编辑:增加错误处理。函数方法的问题是,如果函数不存在,它将杀死整个脚本;使用类和__callstatic,您可以提供优雅的错误处理,并且您只需根据您的需要扩展国家数组-或者更好的是-您可以从其他来源(如数据库)中提取这些国家。

编辑2:切换到PHP5数组语法。清洁。

当你觉得你开始需要对你的代码变得"聪明"时,这是一个糟糕的决定的标志,它会咬你的屁股。

可以使用变量函数

$function = 'filterthis_'. $lang;
$function($form);

如果你可以改变函数,你也可以改变她的名字,并发送lang作为参数

function filterthis($lang, $form) { ... }

您所问的问题没有多大意义(为什么有许多相同的函数??),但可以使用变量变量和闭包:

$list = ['uk','ch','eu'];
foreach($list as $item){
    $filterthis_$item = function(){
        return 'hello';
    }
}
echo $filterthis_uk();
echo $filterthis_ch();
echo $filterthis_eu();