我的PHP函数应该接受参数数组还是应该显式请求参数? [英] Should my PHP functions accept an array of arguments or should I explicitly request arguments?
问题描述
在我正在开发的PHP Web应用程序中,我看到以两种可能的方式定义的函数.
In a PHP web application I'm working on, I see functions defined in two possible ways.
方法1:
function myfunc($arg1, $arg2, $arg3)
方法2:
// where $array_params has the structure array('arg1'=>$val1, 'arg2'=>$val2, 'arg3'=>$val3)
function myfunc($array_params)
我何时应该使用一种方法来替代另一种方法?看来,如果系统要求不断变化,因此myfunc的参数数量不断变化,则方法1可能需要大量维护.
When should I use one approach over another? It seems that if system requirements keep changing, and therefore the number of arguments for myfunc keep changing, approach 1 may require a lot of maintenance.
推荐答案
如果系统变化频繁,以至于使用索引数组是最佳解决方案,那么我想这就是您的后顾之忧. :-)
If the system is changing so often that using an indexed array is the best solution, I'd say this is the least of your worries. :-)
通常,函数/方法不应使用太多参数(5个加减2是最大值),我想说你应该坚持使用named(最好是
In general functions/methods shouldn't take too many arguments (5 plus or minus 2 being the maximum) and I'd say that you should stick to using named (and ideally type hinted) arguments. (An indexed array of arguments only really makes sense if there's a large quantity of optional data - a good example being configuration information.)
就像@Pekka所说的那样,传递一系列参数也很容易记录,因此对于其他人/您自己来说,在n个月内就难以维持.
As @Pekka says, passing an array of arguments is also liable to be a pain to document and therefore for other people/yourself in 'n' months to maintain.
更新程序...
偶然地,经常提到的这本书 代码完整 对此进行了研究问题相当详细-这是我强烈推荐的很棒的书.
Incidentally, the oft mentioned book Code Complete examines such issues in quite a bit of detail - it's a great tome which I'd highly recommend.
这篇关于我的PHP函数应该接受参数数组还是应该显式请求参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!