【问题标题】:How to avoid a really long list of function parameters in PHP?如何避免 PHP 中的函数参数列表很长?
【发布时间】:2018-10-11 09:58:32
【问题描述】:

我的问题是我有很多函数参数列表很长,比如这个:

function select_items($con,$type,$id_item,$item_timestamp,$item_source_url,$item_type,$item_status,$item_blogged_status,$item_viewcount,$item_language,$item_difficulty,$item_sharecount,$item_pincount,$item_commentcount,$item_mainpage,$item_image_width,$item_image_height,$item_image_color,$item_modtime,$order,$start,$limit,$keyword,$language,$id_author,$id_sub_category,$id_category,$id_tag,$id_user){ ... }

正如您所见,它超长而且(当然)很难维护。有时我需要所有变量来构造一个超级复杂的 sql 查询,但有时我只使用其中的 1 或 2 个。有没有办法避免这个庞大的参数列表?例如有一些严格/特殊的命名约定?

所以基本上我需要这样的东西:

$strictly_the_same_param_name="It's working!";

echo hello($strictly_the_same_param_name);


function hello()  //<- no, or flexible list of variables
{
     return $strictly_the_same_param_name; // but still able to recognize the incoming value        
}

// outputs: It's working! 

我考虑过使用 $_GLOBALs / global 或 $_SESSIONs 来解决这个问题,但对我来说似乎并不专业。或者是吗?

【问题讨论】:

  • 使用关联数组作为参数
  • 改用数组,
  • 如果您使用的是 PHP > 5.6,请参阅 Example 13 in this PHP Manual Page
  • 全局变量通常是个坏主意,原因有很多
  • 你的函数可能太复杂了,句号。如果这些参数中的大多数都是可选的,那可能意味着你也有大量的if..else 语句,这很糟糕。解决这个问题的唯一方法是适当的软件工程,将功能分解为单独的函数/对象/可组合对象/whatnot。

标签: php variables parameters scope


【解决方案1】:

第一步,正如您所说,有时您只需要使用 2 个参数调用函数,您可以在函数声明中为您的参数设置默认值。这将允许您使用 25 个参数中的 2 个来调用您的函数。

例如:

function foo($mandatory_arg1, $optional_arg = null, $opt_arg2 = "blog_post") {
    // do something
}

在第二步中,您可以使用数组,尤其是在这种情况下,数组会更简单:

function foo(Array $params) {
    // then here test your keys / values
}

第三步,也可以使用Variable-length argument lists(在页面中搜索“...”):

function sum(...$numbers) {
    $acc = 0;
    foreach ($numbers as $n) {
        $acc += $n;
    }
    return $acc;
}

但归根结底,我认为你应该使用对象来处理这些事情;)

【讨论】:

  • 谢谢@WizardNx,这非常有帮助!
【解决方案2】:

你可以尝试使用...令牌:

$strictly_the_same_param_name= ["It's working!"];

echo hello($strictly_the_same_param_name);


function hello(...$args)  //<- no, or flexible list of variables
{
    if ( is_array( $args ) {
    $key = array_search( 'What you need', $args );
         if ( $key !== false ) {
             return $args[$key];
         }
    }
    return 'Default value or something else';
}

【讨论】:

    猜你喜欢
    • 2017-12-28
    • 1970-01-01
    • 2020-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-08
    • 2020-09-10
    • 2012-11-28
    相关资源
    最近更新 更多