【发布时间】: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