我如何在第一个可选参数之后在PHP中设置可选参数 [英] How do i set an optional parameter in PHP after the first optional parameter

查看:56
本文介绍了我如何在第一个可选参数之后在PHP中设置可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对php还是很陌生,我想弄清楚如何在第一个可选参数之后设置可选参数?

I'm fairly new to php and I am trying to figure how do I set an optional parameter after the first optional parameter?

例如,我有以下代码:

function testParam($fruit, $veg='pota',$test='default test'){
echo '<br>$fruit = '.$fruit;
echo '<br>$veg = '.$veg;
echo '<br>Test = '.$test;
}

如果我打以下电话:

echo 'with all parama';
testParam('apple','carrot','some string');
//we get:
//with all parama
//$fruit = apple
//$veg = carrot
//Test = some string

echo '<hr> missing veg';
testParam('apple','','something');
//we get:
//missing veg
//$fruit = apple
//$veg = 
//Test = something

echo '<hr> This wont work';
testParam('apple',,'i am set');

我想尝试拨打电话,以便在上一个示例中将"pota"显示为默认的$ veg参数,但将其传递给$ test我被设置".

I want to try make a call so that in the last example I show 'pota' as the default $veg parameter but pass into $test 'i am set'.

我想我可以将0传递给$ veg,然后在代码中将其分支,以说明$ veg = 0,然后使用'pota',但是我想知道是否还有其他语法,因为我无法在php.net中找到有关它的任何内容.

I guess I can pass 0 into $veg then branch it in the code to say if $veg =0 then use 'pota' but just wondered if there's some other syntax as i cant find anything in php.net about it.

推荐答案

仅使用默认参数就无法做您想做的事情.默认值仅适用于缺少的参数,只有最后一个参数可以丢失.

You can't do what you want with just default parameters. The defaults only apply to missing arguments, and only the last argument(s) can be missing.

您可以添加以下行

  $vega = $vega ? $vega : 'carrot';

并以

testParam('apple',false,'something');

或使用更通用的技术,以参数名称作为键在数组中传递参数.像

or use the more general technique of passing the parameters in an array with the parameter names as keys. Something like

function testparam($parms=false) {
    $default_parms = array('fruit'=>'orange', 'vega'=>'peas', 'starch'=>'bread');
    $parms = array_merge($default_parms, (array) $parms);
    echo '<br>fruit  = $parms[fruit]';
    echo '<br>vega   = $parms[vega]';
    echo '<br>starch = $parms[starch]';
}

testparm('starch'=>'pancakes');
//we get:
//fruit = orange
//vega  = peas
//starch = pancakes

这有点冗长,但也更灵活.您可以添加参数和默认值,而无需更改现有的调用方.

This is a little more verbose but it is also more flexible. You can add parameters and defaults without changing the existing callers.

这篇关于我如何在第一个可选参数之后在PHP中设置可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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