PHP 默认函数参数值,如何为“非最后"参数“传递默认值"? [英] PHP Default Function Parameter values, how to 'pass default value' for 'not last' parameters?

查看:27
本文介绍了PHP 默认函数参数值,如何为“非最后"参数“传递默认值"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们大多数人都知道以下语法:

Most of us know the following syntax:

function funcName($param='value'){
    echo $param;
}
funcName();

Result: "value"

我们想知道如何为not last"参数传递默认值?我知道这个术语有点过时,但一个简单的例子是:

We were wondering how to pass default values for the 'not last' paramater? I know this terminology is way off, but a simple example would be:

function funcName($param1='value1',$param2='value2'){
    echo $param1."
";
    echo $param2."
";
}

我们如何完成以下工作:

How do we accomplsh the following:

funcName(---default value of param1---,'non default');

结果:

value1
not default

希望这是有道理的,我们希望基本上假设不是最后的参数的默认值.

Hope this makes sense, we want to basically assume default values for the paramaters which are not last.

谢谢.

推荐答案

PHP 不支持您尝试执行的操作.这个问题的通常解决方案是传递一个参数数组:

PHP doesn't support what you're trying to do. The usual solution to this problem is to pass an array of arguments:

function funcName($params = array())
{
    $defaults = array( // the defaults will be overidden if set in $params
        'value1' => '1',
        'value2' => '2',
    );

    $params = array_merge($defaults, $params);

    echo $params['value1'] . ', ' . $params['value2'];
}

示例用法:

funcName(array('value1' => 'one'));                    // outputs: one, 2
funcName(array('value2' => 'two'));                    // outputs: 1, two
funcName(array('value1' => '1st', 'value2' => '2nd')); // outputs: 1st, 2nd
funcName();                                            // outputs: 1, 2

使用这个,所有参数都是可选的.通过传递参数数组,数组中的任何内容都将覆盖默认值.这可以通过使用 array_merge() 合并两个数组,用第二个数组中的任何重复元素覆盖第一个数组.

Using this, all arguments are optional. By passing an array of arguments, anything that is in the array will override the defaults. This is possible through the use of array_merge() which merges two arrays, overriding the first array with any duplicate elements in the second array.

这篇关于PHP 默认函数参数值,如何为“非最后"参数“传递默认值"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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