php 如何在函数调用中跳过可选参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1066625/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:51:09  来源:igfitidea点击:

How would I skip optional arguments in a function call?

phpfunctionparametersdefault-valueoptional-parameters

提问by

OK I totally forgot how to skip arguments in PHP.

好吧,我完全忘记了如何在 PHP 中跳过参数。

Lets say I have:

可以说我有:

function getData($name, $limit = '50', $page = '1') {
    ...
}

How would I call this function so that the middle parameter takes the default value (ie. '50')?

我将如何调用此函数以便中间参数采用默认值(即“50”)?

getData('some name', '', '23');

Would the above be correct? I can't seem to get this to work.

以上会正确吗?我似乎无法让它发挥作用。

回答by zombat

Your post is correct.

你的帖子是正确的。

Unfortunately, if you need to use an optional parameter at the very end of the parameter list, you have to specify everything up until that last parameter. Generally if you want to mix-and-match, you give them default values of ''or null, and don't use them inside the function if they are that default value.

不幸的是,如果您需要在参数列表的最后使用可选参数,则必须指定直到最后一个参数为止的所有内容。一般来说,如果你想混合搭配,你给它们默认值''or null,如果它们是默认值,不要在函数内部使用它们。

回答by Paolo Bergantino

There's no way to "skip" an argument other than to specify a default like falseor null.

除了指定默认值,如false或之外,没有办法“跳过”参数null

Since PHP lacks some syntactic sugar when it comes to this, you will often see something like this:

由于 PHP 在这方面缺少一些语法糖,因此您经常会看到如下内容:

checkbox_field(array(
    'name' => 'some name',
    ....
));

Which, as eloquently said in the comments, is using arrays to emulate named arguments.

正如评论中雄辩地说的那样,它使用数组来模拟命名参数。

This gives ultimate flexibility but may not be needed in some cases. At the very least you can move whatever you think is not expected most of the time to the end of the argument list.

这提供了最大的灵活性,但在某些情况下可能不需要。至少,您可以将大多数情况下您认为不期望的任何内容移动到参数列表的末尾。

回答by Cristik

Nope, it's not possible to skip arguments this way. You can omit passing arguments onlyif they are at the end of the parameter list.

不,不可能以这种方式跳过参数。只有当参数位于参数列表的末尾时,您才能省略传递参数。

There was an official proposal for this: https://wiki.php.net/rfc/skipparams, which got declined. The proposal page links to other SO questions on this topic.

对此有一个官方提议:https: //wiki.php.net/rfc/skipparams,但遭到拒绝。提案页面链接到有关此主题的其他 SO 问题。

回答by Ibrahim Lawal

Nothing has changed regarding being able to skip optional arguments, however for correct syntax and to be able to specify NULL for arguments that I want to skip, here's how I'd do it:

关于能够跳过可选参数没有任何改变,但是为了正确的语法并能够为我想要跳过的参数指定 NULL,我会这样做:

define('DEFAULT_DATA_LIMIT', '50');
define('DEFAULT_DATA_PAGE', '1');

/**
 * getData
 * get a page of data 
 *
 * Parameters:
 *     name - (required) the name of data to obtain
 *     limit - (optional) send NULL to get the default limit: 50
 *     page - (optional) send NULL to get the default page: 1
 * Returns:
 *     a page of data as an array
 */

function getData($name, $limit = NULL, $page = NULL) {
    $limit = ($limit===NULL) ? DEFAULT_DATA_LIMIT : $limit;
    $page = ($page===NULL) ? DEFAULT_DATA_PAGE : $page;
    ...
}

This can the be called thusly: getData('some name',NULL,'23');and anyone calling the function in future need not remember the defaults every time or the constant declared for them.

这可以这样getData('some name',NULL,'23');调用:将来调用该函数的任何人都不需要每次都记住默认值或为它们声明的常量。

回答by Nelson Owalo

The simple answer is No. But why skip when re-arranging the arguments achieves this?

简单的答案是否定的。但是为什么在重新排列参数时跳过会实现这一点呢?

Yours is an "Incorrect usage of default function arguments" and will not work as you expect it to.

你的是“默认函数参数的错误使用”,不会像你期望的那样工作。

A side note from the PHP documentation:

PHP 文档中的附注:

When using default arguments, any defaults should be on the right side of any non-default arguments; otherwise, things will not work as expected.

使用默认参数时,任何默认值都应该在任何非默认参数的右侧;否则,事情将不会按预期进行。

Consider the following:

考虑以下:

function getData($name, $limit = '50', $page = '1') {
    return "Select * FROM books WHERE name = $name AND page = $page limit $limit";
}

echo getData('some name', '', '23');   // won't work as expected

The output will be:

输出将是:

"Select * FROM books WHERE name = some name AND page = 23 limit"

The Correct usage of default function arguments should be like this:

默认函数参数的正确用法应该是这样的:

function getData($name, $page = '1', $limit = '50') {
    return "Select * FROM books WHERE name = $name AND page = $page limit $limit";
}

echo getData('some name', '23');  // works as expected

The output will be:

输出将是:

"Select * FROM books WHERE name = some name AND page = 23 limit 50"

Putting the default on your right after the non-defaults makes sure that it will always retun the default value for that variable if its not defined/given Here is a linkfor reference and where those examples came from.

在非默认值之后将默认值放在您的右侧,以确保它在未定义/给定的情况下始终重新调整该变量的默认值这是一个参考链接以及这些示例的来源。

Edit: Setting it to nullas others are suggesting might work and is another alternative, but may not suite what you want. It will always set the default to null if it isn't defined.

编辑:将其设置null为其他人建议的可能有效并且是另一种选择,但可能不适合您想要的。如果未定义,它将始终将默认值设置为 null。

回答by Vlad Isoc

You can't skip arguments but you can use array parameters and you need to define only 1 parameter, which is an array of parameters.

你不能跳过参数,但你可以使用数组参数,你只需要定义 1 个参数,它是一个参数数组。

function myfunction($array_param)
{
    echo $array_param['name'];
    echo $array_param['age'];
    .............
}

And you can add as many parameters you need, you don't need to define them. When you call the function, you put your parameters like this:

您可以添加任意数量的参数,无需定义它们。当您调用该函数时,您将参数放置如下:

myfunction(array("name" => "Bob","age" => "18", .........));

回答by Voitcus

As mentioned above, you will not be able to skip parameters. I've written this answer to provide some addendum, which was too large to place in a comment.

如上所述,您将无法跳过参数。我写这个答案是为了提供一些附录,它太大而无法放在评论中。

@Frank Nocke proposesto call the function with its default parameters, so for example having

@Frank Nocke建议使用其默认参数调用该函数,例如

function a($b=0, $c=NULL, $d=''){ //...

you should use

你应该使用

$var = a(0, NULL, 'ddd'); 

which will functionally be the same as omitting the first two ($band $c) parameters.

这在功能上与省略前两个 ($b$c) 参数相同。

It is not clear which ones are defaults (is 0typed to provide default value, or is it important?).

不清楚哪些是默认值(0输入是为了提供默认值,还是很重要?)。

There is also a danger that default values problem is connected to external (or built-in) function, when the default values could be changed by function (or method) author. So if you wouldn't change your call in the program, you could unintentionally change its behaviour.

当默认值可以由函数(或方法)作者更改时,默认值问题也存在与外部(或内置)函数相关的危险。因此,如果您不更改程序中的调用,则可能会无意中更改其行为。

Some workaround could be to define some global constants, like DEFAULT_A_Bwhich would be "default value of B parameter of function A" and "omit" parameters this way:

一些解决方法可能是定义一些全局常量,例如DEFAULT_A_B“函数 A 的 B 参数的默认值”和“省略”参数这样的:

$var = a(DEFAULT_A_B, DEFAULT_A_C, 'ddd');

For classes it is easier and more elegant if you define class constants, because they are part of global scope, eg.

对于类,如果定义类常量会更容易和更优雅,因为它们是全局范围的一部分,例如。

class MyObjectClass {
  const DEFAULT_A_B = 0;

  function a($b = self::DEFAULT_A_B){
    // method body
  }
} 
$obj = new MyObjectClass();
$var = $obj->a(MyObjectClass::DEFAULT_A_B); //etc.

Note that this default constant is defined exactly once throughout the code (there is no value even in method declaration), so in case of some unexpected changes, you will always supply the function/method with correct default value.

请注意,这个默认常量在整个代码中只定义了一次(即使在方法声明中也没有值),因此如果发生一些意外更改,您将始终为函数/方法提供正确的默认值。

The clarity of this solution is of course better than supplying raw default values (like NULL, 0etc.) which say nothing to a reader.

该解决方案的清晰度当然不是提供原始默认值(比如更好的NULL0等等),这没什么好说的读者。

(I agree that calling like $var = a(,,'ddd');would be the best option)

(我同意像这样打电话$var = a(,,'ddd');是最好的选择)

回答by Frank Nocke

For any parameter skipped (you have to) go with the default parameter, to be on the safe side.

对于跳过的任何参数(您必须)使用默认参数,以确保安全。

(Settling for null where the default parameter is '' or similar or vice versa will get you into troublew...)

(在默认参数为 '' 或类似的情况下设置为 null ,反之亦然会使您陷入困境......)

回答by Rizier123

Well as everyone else already said, that what you want won't be possible in PHP without adding any code lines in the function.

正如其他人已经说过的那样,如果不在函数中添加任何代码行,您想要的东西在 PHP 中是不可能的。

But you can place this piece of code at the top of a function to get your functionality:

但是您可以将这段代码放在函数的顶部以获得您的功能:

foreach((new ReflectionFunction(debug_backtrace()[0]["function"]))->getParameters() as $param) {
    if(empty(${$param->getName()}) && $param->isOptional())
        ${$param->getName()} = $param->getDefaultValue();
}

So basically with debug_backtrace()I get the function name in which this code is placed, to then create a new ReflectionFunctionobject and loop though all function arguments.

所以基本上debug_backtrace()我得到了放置这段代码的函数名,然后创建一个新ReflectionFunction对象并循环遍历所有函数参数。

In the loop I simply check if the function argument is empty()AND the argument is "optional" (means it has a default value). If yes I simply assign the default value to the argument.

在循环中,我只是检查函数参数是否为empty()AND 参数是否为“可选”(意味着它具有默认值)。如果是,我只是将默认值分配给参数。

Demo

Demo

回答by Hari Kumar

Set the limit to null

将限制设置为空

function getData($name, $limit = null, $page = '1') {
    ...
}

and call to that function

并调用该函数

getData('some name', null, '23');

if you want to set the limit you can pass as an argument

如果你想设置限制,你可以作为参数传递

getData('some name', 50, '23');