PHP可变长度参数? [英] PHP variable length arguments?

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

问题描述

在Python和其他语言中,可变长度参数列表有特殊的语法:

  def do_something(* args):
#做某事

do_something(1,2,3,4,5,...)#任意长列表

我正在阅读PHP手册,并说:


PHP 4及以上在
用户定义函数中支持
变长参数列表。这实际上非常简单,使用func_num_args(),
func_get_arg()和func_get_args()
函数。

否特殊的语法是必需的,
参数列表可能仍然是明确的
提供了函数定义,
将像正常一样运行。


我得到第一部分。您可以根据需要传递多个参数,而不需要任何参数,然后使用 func_get_args()等将它们作为数组获取。我并不真正所以,我的问题是,是否有一些特殊的可变长度参数语法,或一些最佳做法,我不知道知道关于?手册中提到的方法似乎最好是kludgey,并且使得你的函数看起来像没有任何参数(除非我做错了)。我不应该试图使用这种语言功能吗?

解决方案

与Python的 * 运算符或C#的 params 关键字,在PHP中,您甚至不必指定可变长度参数。第二部分开始时,不需要特殊的语法。



至于第二段的其余部分:如果您想指定任何必需或不相关的参数在可变长度参数之前,在函数签名中指定它们,以便您的函数可以处理这些参数。然后,获取可变长度参数,从 func_get_args()中移除所需的变量,如下所示:

<$ p $函数func($ required){
//包含所有在$ required
之后的参数,因为它们在调用时存在
$ args = array_slice (func_get_args(),1);



$ b你不必这样做(你仍然可以从 func_get_args()并相应地使用它的不同元素),但它确实使您的代码更加自我记录。


In Python and others, there's special syntax for variable length argument lists:

def do_something(*args):
    # do something

do_something(1, 2, 3, 4, 5, ...) # arbitrarily long list

I was reading the PHP manual, and it said this:

PHP 4 and above has support for variable-length argument lists in user-defined functions. This is really quite easy, using the func_num_args(), func_get_arg(), and func_get_args() functions.

No special syntax is required, and argument lists may still be explicitly provided with function definitions and will behave as normal.

I get the first part. You can pass as many arguments as you'd like to a function that takes no arguments, then get them as an array using func_get_args(), etc. I don't really get what the second part is saying, though.

So, my question is, is there some special syntax for variable length arguments, or some best practice that I don't know about? The approach that the manual suggests seems kludgey at best and makes your function seem like it's taking no arguments (unless I'm doing it wrong). Should I not be trying to use this language feature at all?

解决方案

Unlike Python's * operator or C#'s params keyword, in PHP you don't even have to specify the variable length arguments. As the second part starts off, "No special syntax is required."

As to the rest of the second paragraph: if you want to specify any required or unrelated arguments that come before the variable-length arguments, specify them in your function signature so your function can handle those. Then to get the variable-length arguments, remove the required variables from func_get_args(), like so:

function func($required) {
    // Contains all arguments that come after $required
    // as they were present at call time
    $args = array_slice(func_get_args(), 1);
}

You don't have to do this (you can still slice from func_get_args() and use its different elements accordingly), but it does make your code more self-documenting.

这篇关于PHP可变长度参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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