如何使用动态创建的参数调用静态类方法


How to call a static class method with dynamically created arguments?

我正在使用jQuery插件dataTables在网站上创建一个可编辑的表,我正试图使对fields方法的调用动态接受参数:

Editor::inst( $db, $table, $primary_key )
    ->fields(
        // this part needs to be dynamic
        Field::inst( 'value1' )
            ->validator( 'Validate::numeric' ),
        Field::inst( 'value2' )
            ->validator( 'Validate::numeric' )
    )
    ->process( $_POST )
    ->json();

数组中有value1和value2,但可以有两个以上。数字取决于我想要创建的表:

$columns = array("value1", "value2");

如何在方法调用中获取它们,以便正确评估所有内容?

我真的不想使用大小写。必须有更好的方法来做到这一点。

来自数据表文档。

fields()方法可以接受任意数量的字段实例,也可以多次调用以添加其他字段。

$columns = array('value1', 'value2');
$editor = Editor::inst($db, $table, $primary_key);
foreach ($columns as $field) {
    $editor->fields(Field::inst($field)->validator('Validate::numeric'));
}
$editor->process($_POST)
    ->json();

您还可以使用以下内容使验证器动态:

$columns = array('value1' => 'Validate::numeric', 'value2' => 'Validate::notEmpty');
$editor = Editor::inst($db, $table, $primary_key);
foreach ($columns as $field => $validator) {
    $editor->fields(Field::inst($field)->validator($validator));
}
$editor->process($_POST)
    ->json();

您可以使用func_get_args()和func_num_args)函数来处理动态参数。

你可以这样使用它们,

function yourFunction() {
    $totalParams=func_num_args();    
    echo "Total parameters: ".$totalParams;
    $params = func_get_args();
    foreach($params as $i=>$param) {
         // $param is passed value.
         // $i is the index.
    }
}

就这样叫funtion吧,

yourFunction('param1value','param2value','param3value');

func_num_args()返回传递给函数的参数数

func_get_args()返回一个包含函数参数列表的数组。