PHP传递数组来运行 [英] PHP passing array to function

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

问题描述

我见过一些人提出类似的问题。但我确实需要对这个特定主题进行更多的说明。



我有几个函数传递了几个参数。我甚至有几个大约10个参数。 (最初没有计划,只是随着时间的推移而增长)

我没有任何问题看我的源代码来找出第七个参数是什么,但它确实很乏味。我大部分时间都知道要传递什么参数,而不是位置。



我有一些想法来简化流程。



a)传递1个参数,但用一些分隔符分隔所有内容。 (但这是一个坏主意!,因为我仍然需要记住每个位置。

  function myfunc('data | data | data |'){
//爆炸字符串
}

b )传递一个包含键和值的数组,并在我的函数中查找键名,并相应地执行。

  function myfunc array('arg1'=>'blah blah','arg2'=>'more blah')){
//遍历数组
}

c)保持原状。

  function myfunc($ arg1,$ arg2,$ arg3,$ arg4,$ arg5 ........){
// yay

}

所以,我正在寻找其他选项和更好的想法来处理越来越多参数列表的函数。


)(关联数组)是迄今为止最简单,最具适应性(因为它允许模拟默认关键字参数),并且最不容易出错的变体。

I've seen a few people ask a similar question. But I do need a little more clarification on this particular subject.

I have several functions that pass several arguments. I even have a few that are about 10 arguments. (didn't initially plan it, simply grew over time)

I don't have any problems looking at my source code to find out what the 7th argument is, but it does get tedious. Most of the time I know what arguments to pass, just not the position.

I had a few ideas to simplify the process for me.

a) pass 1 argument, but divide everything with some delimiter. (but that's a bad idea!, since I still need to remember the position of each.

function myfunc('data|data|data|'){
          // explode the string
}

b) pass an array with key and values, and look for the key names inside my function, and act accordingly.

function myfunc(array('arg1' => 'blah blah', 'arg2' => 'more blah')){
  // loop through the array
}

c) keep it as it is.

function myfunc($arg1,$arg2,$arg3,$arg4,$arg5........){
// yay

}

So, I'm seeking other options and better ideas for handling functions with growing argument lists.

解决方案

b) (an associative array) is by far the easiest, most adaptible (as it allows simulating default keyword arguments), and least error-prone variant.

这篇关于PHP传递数组来运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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