Home  >  Article  >  Backend Development  >  PHP中可选参数是不是必须在必选参数之后?

PHP中可选参数是不是必须在必选参数之后?

WBOY
WBOYOriginal
2016-06-06 20:52:222276browse

public function addHost($groupId, $nodeId = "node_0", $role = "master", $hostConfig)
{
    //.....
}

在我映象中一直都是必选参数定义在可选参数之前的,上面这段代码是在 lotusphp 中看到的源码,请问这样定义如何使用呢?

回复内容:

public function addHost($groupId, $nodeId = "node_0", $role = "master", $hostConfig)
{
    //.....
}

在我映象中一直都是必选参数定义在可选参数之前的,上面这段代码是在 lotusphp 中看到的源码,请问这样定义如何使用呢?

function test($a, $b = 3, $c = 4 ,$d) {
    echo $a.$b.$c.$d;
}

echo test(4, "", "", 9);
//打印结果
//49

echo test(4, null, null, 9);
//打印结果
//49

实际上 $b = 3, $c = 4 的默认值永远不会设置成功的。
如果第四个参数是必选参数,那么使用函数时必须有四个以上参数,此时默认参数无意义。

1. 你的印象不正确,必选参数和可选参数没有顺序的,不一定要把可选参数放在最后
2. lotusphp的addHost()方法设计成这样,主要是因为group, node, role在概念层次上是渐进的,颠倒次序逻辑上不利于记忆,而config
3. 调用方法就是addHost("global_group", , , array("host"=> "127.0.0.1")),更多调用方法请参见lotusphp/unittest/Db/RightWayToUse.php

楼上正解,php中不讲究默认参数的位置,但是调用的时候又不能隔开,如
function test($a,$b=3,$c=4 ,$d)
{
echo $a.$b.$c.$d;
}
echo test(1,2,3,5);//可以通过
echo test(1,,,5);//错误

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn