zac*_*zap 21 php function optional-parameters
假设我有一个PHP函数foo:
function foo($firstName = 'john', $lastName = 'doe') {
echo $firstName . " " . $lastName;
}
// foo(); --> john doe
Run Code Online (Sandbox Code Playgroud)
有没有办法只指定第二个可选参数?
例:
foo($lastName='smith'); // output: john smith
Run Code Online (Sandbox Code Playgroud)
Noa*_*ich 32
PHP不支持函数本身的命名参数.但是,有一些方法可以解决这个问题:
cee*_*yoz 22
阵列技术的一种变体,可以更容易地设置默认值:
function foo($arguments) {
$defaults = array(
'firstName' => 'john',
'lastName' => 'doe',
);
$arguments = array_merge($defaults, $arguments);
echo $arguments['firstName'] . ' ' . $arguments['lastName'];
}
Run Code Online (Sandbox Code Playgroud)
用法:
foo(array('lastName' => 'smith')); // output: john smith
Run Code Online (Sandbox Code Playgroud)
你可以稍微重构你的代码:
function foo($firstName = NULL, $lastName = NULL)
{
if (is_null($firstName))
{
$firstName = 'john';
}
if (is_null($lastName ))
{
$lastName = 'doe';
}
echo $firstName . " " . $lastName;
}
foo(); // john doe
foo('bill'); // bill doe
foo(NULL,'smith'); // john smith
foo('bill','smith'); // bill smith
Run Code Online (Sandbox Code Playgroud)
如果您有多个可选参数,则一种解决方案是传递一个哈希数组参数:
function foo(array $params = array()) {
echo $params['firstName'] . " " . $params['lastName'];
}
foo(array('lastName'=>'smith'));
Run Code Online (Sandbox Code Playgroud)
当然,在此解决方案中,无法验证散列数组的字段是否存在或拼写正确.完全由您来验证.
| 归档时间: |
|
| 查看次数: |
18681 次 |
| 最近记录: |