将参数数组与单个参数传递给PHP中的函数? [英] Passing array of parameters vs. individual parameters to a function in PHP?

查看:137
本文介绍了将参数数组与单个参数传递给PHP中的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当有一个函数需要传递多个参数,例如七个参数,这是更好的做法:

  function foo($ par1,$ par2,$ par3,$ par4,$ par5,$ par6,$ par7)
{
}
pre>

  function foo(array $ args)
{
}

在第二个示例中 $ args



我一直使用这两种方法不一致。



使用第一种方法的缺点是,如果你得到的参数的顺序错了,你被拧了(它可能真的很难调试,因为它并不总是明显)。这是使用数组方法的优点。



使用第一种类型的优点是,一个好的PHP编辑器如PhpStorm会显示你的名字您可以在输入函数时查看参数,这比查看需要在数组中传递哪些参数更容易。



感谢您的建议。理论上,每个参数应该包含一个逻辑整体。每个参数都包含一个逻辑整数。集合旨在表示值的集合,而不是方法参数的聚合;单独的参数应该单独传递以清楚地表示方法的目的。



实际上,当在数组中传递参数时,你必须进行大量手动检查确保已经通过正确的参数。您可以通过提供参数清晰,逻辑名称(和可能的类型提示)避免几乎任何歧义。



编辑:如果你的方法/函数

em>接受一组模糊定义的选项,这些选项会影响代码仅以次要方式执行的操作,请考虑使用Symfony OptionsResolver 组件,以极大地简化对选项数组的验证。


When there is a function that requires a number of parameters to be passed, such as seven parameters, which is the better practice:

function foo($par1, $par2, $par3, $par4, $par5, $par6, $par7)
{
}

or

function foo(array $args)
{
}

Where in the second example $args would an array with the parameters as elements.

I have been inconsistently using both methods.

The disadvantage to using the first method is that if you get order of a parameter wrong, you're screwed (and it could be really hard to debug because it's not always obvious). This is the advantage of using the array method.

The advantage (IMHO) of using the first type is that a good PHP editor such as PhpStorm will show you the names of the parameters as you are typing the function, which is easier than going to the function to see what parameters need to be passed in an array.

Appreciate your advice.

解决方案

Theoretically, each parameter should encompass a logical whole. Collections are meant to represent a collection of values, not an aggregate of method parameters; the individual parameters should be passed separately to clearly indicate the purpose of the method.

Practically, when passing parameters in an array, you have to do a ton of manual checks to ensure that correct parameters have been passed. You can avoid pretty much any ambiguity by giving your parameters clear, logical names (and typehints where possible). Also, as a comment already stated, if a method takes 7 parameters, it's probably ripe for some refactoring.

Edit: if your method/function does accept a set of vaguely defined "options" that affect what the code does only in a minor way, consider using the Symfony OptionsResolver component, to greatly ease the validation of your options array.

这篇关于将参数数组与单个参数传递给PHP中的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆