任何方式来指定PHP中的可选参数值? [英] Any way to specify optional parameter values in PHP?

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

问题描述

 函数foo($ firstName ='john',$ lastName ='doe'){
echo $ firstName。 。 $ lastName的;
}
// foo(); - > john doe

有没有什么办法可以指定第二个可选参数?



示例:

  foo($ lastName ='smith'); //输出:john smith 


解决方案

PHP不支持named功能本身的参数。但是,有一些方法可以解决这个问题:


  1. 使用数组作为函数的唯一参数。然后你可以从数组中提取值。这允许在数组中使用命名参数。

  2. 如果要根据上下文允许可选数量的参数,则可以使用func_num_args和func_get_args,而不是在函数中指定有效参数定义。然后根据参数的数量,字符串长度等,您可以确定要执行的操作。
  3. 将空值传递给您不想指定的参数。如果你在一个对象上下文中工作,那么你可以使用魔术方法__call()来处理这些类型的请求,这样你就可以可以根据传递的参数路由到私有方法。


Let's say I've got a PHP function foo:

function foo($firstName = 'john', $lastName = 'doe') {
    echo $firstName . " " . $lastName;
}
// foo(); --> john doe

Is there any way to specify only the second optional parameter?

Example:

foo($lastName='smith'); // output: john smith

解决方案

PHP does not support named parameters for functions per se. However, there are some ways to get around this:

  1. Use an array as the only argument for the function. Then you can pull values from the array. This allows for using named arguments in the array.
  2. If you want to allow optional number of arguments depending on context, then you can use func_num_args and func_get_args rather than specifying the valid parameters in the function definition. Then based on number of arguments, string lengths, etc you can determine what to do.
  3. Pass a null value to any argument you don't want to specify. Not really getting around it, but it works.
  4. If you're working in an object context, then you can use the magic method __call() to handle these types of requests so that you can route to private methods based on what arguments have been passed.

这篇关于任何方式来指定PHP中的可选参数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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