【问题标题】:How to call a static class method with dynamically created arguments?如何使用动态创建的参数调用静态类方法?
【发布时间】:2016-07-20 09:42:06
【问题描述】:

我正在使用 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");

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

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

【问题讨论】:

    标签: php class methods static datatables


    【解决方案1】:

    来自数据表文档。

    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();
    

    【讨论】:

      【解决方案2】:

      您可以使用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.
          }
      }
      

      像这样调用函数,

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

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

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

      【讨论】:

      • 您确定这对我的特定用例有用吗?我不能那样调用函数,因为我不知道会有多少参数。
      • 正如我所提到的,这两个函数不依赖于您调用该函数的方法。它可以帮助您在不知道实际数字的情况下将所有参数传递给函数。
      • 在你的函数中使用 func_get_args() 使用 foreach 来访问你的所有参数,并使用它们来绑定查询或其他任何东西。
      • func_get_args(): Called from the global scope - no function context ...
      • 这可能会帮助您解决php.net/manual/en/function.func-get-arg.php 它列出了相同的错误。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多