PHP是否允许命名参数,以便可以从函数调用中省略可选参数? [英] Does PHP allow named parameters so that optional arguments can be omitted from function calls?

查看:66
本文介绍了PHP是否允许命名参数,以便可以从函数调用中省略可选参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在调用函数/方法时,是否有可能在PHP中指定一个命名的可选参数,从而跳过了您不想指定的参数(如python)?

Is it possible in PHP to specify a named optional parameter when calling a function/method, skipping the ones you don't want to specify (like in python)?

类似的东西:

function foo($a, $b = '', $c = '') {
    // whatever
}


foo("hello", $c="bar"); // we want $b as the default, but specify $c

推荐答案

否,这是不可能的:如果要传递第三个参数,则必须传递第二个参数.而且命名参数也不可能.

No, it is not possible : if you want to pass the third parameter, you have to pass the second one. And named parameters are not possible either.


一种解决方案"是仅使用一个参数,一个数组并始终传递它……但不要总是在其中定义所有内容.


A "solution" would be to use only one parameter, an array, and always pass it... But don't always define everything in it.

例如:

function foo($params) {
    var_dump($params);
}

并以这种方式调用它:

foo(array(
    'a' => 'hello',
));

foo(array(
    'a' => 'hello',
    'c' => 'glop',
));

foo(array(
    'a' => 'hello',
    'test' => 'another one',
));

将为您提供此输出:

array
  'a' => string 'hello' (length=5)

array
  'a' => string 'hello' (length=5)
  'c' => string 'glop' (length=4)

array
  'a' => string 'hello' (length=5)
  'test' => string 'another one' (length=11)

但是我不太喜欢这种解决方案:

But I don't really like this solution :

  • 您将丢失phpdoc
  • 您的IDE将不再能够提供任何提示...这很糟糕

因此,仅在非常特殊的情况下才使用此方法-例如,对于具有很多选项参数的函数...

So I'd go with this only in very specific cases -- for functions with lots of optionnal parameters, for instance...

这篇关于PHP是否允许命名参数,以便可以从函数调用中省略可选参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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