帮助将参数传递给函数 [英] help with passing arguments to function

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

问题描述

 函数get_tags_by_criteria($ gender =%,$ min_age_of_birth =%,$ max_age_of_birth =%,$ country =%,$ region =%, $ city =%,$ tag =){

当我只想通过标签参数,并让其他人默认情况下,我怎么写?



我试过这个,但它没有工作。

  get_tags_by_criteria(,,,,,,computer); 


解决方案

您可以使用关联数组模拟命名参数: / p>

 函数my_function($ options)
{
extract($ options);
}

然后调用

  my_function(array(parameter1=>value1,parameter2=>value2)); 

,它与功能内部的强大检查和默认值表结合在一起,对我来说非常合适。

缺点:没有phpDoc惯例来记录参数,并且当您键入时,您的IDE将无法显示可用的参数。您必须将可用参数输入到 @desc 块中,这取决于您的IDE,可能看起来也可能不太好。



对此的一种解决方法是声明函数中的所有参数,但将所有参数都设为可选参数。第一个可以是包含值的关联数组。


function get_tags_by_criteria($gender="%", $min_age_of_birth="%", $max_age_of_birth="%", $country="%", $region="%", $city="%", $tag="") {

when i just want to pass the tag argument and let the others by default, how do i write?

ive tried this but it didnt work.

    get_tags_by_criteria("", "", "", "", "", "", computer);

解决方案

You can simulate named arguments using an associative array:

function my_function($options)
 {
  extract($options);
 }

then call

my_function(array("parameter1" => "value1", "parameter2" => "value2"));

that, combined with robust checking and table of default values inside the function, works very nicely for me.

Downside: There is no phpDoc convention to document the arguments, and your IDE will not be able to show the available arguments to you as you type. You will have to enter the available parameters into the @desc block which, depending on your IDE, may or may not look nice.

One workaround for this is to declare all the parameters in the function, but make all of them but the first one optional. The first one can then be the associative array containing the values.

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

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