有没有一种方法可以根据()中传递的内容只返回函数的一部分?例如:
function test($wo) {
if function contains $wo and "date" {
//pass $wo through sql query to pull date
return $date
}
if function contains $wo and "otherDate" {
//pass $wo through another sql query to pull another date
return $otherDate
}
if function only contains $wo {
//pass these dates through different methods to get a final output
return $finaldate
}
}
日期:
test($wo, date);
退货:
1/1/2015
其他日期:
test($wo, otherDate);
退货:
10/01/2015
正常输出:
test($wo);
退货:
12/01/2015
传递一个指定返回内容的参数:
function test($wo, $type='final') {
// pull $date
if($type == 'date') { return $date; }
// pull $otherdate
if($type == 'other') { return $otherdate; }
// construct $finaldate
if($type == 'final') { return $finaldate; }
return false;
}
然后调用类似:
$something = test($a_var, 'other');
// or for final since it is default
$something = test($a_var);
你的问题很模糊,但如果我理解正确,你需要可选的参数。通过在函数定义中为函数参数提供默认值,可以使函数参数可选:
// $a is required
// $b is optional and defaults to 'test' if not specified
// $c is optional and defaults to null if not specified
function test($a, $b = 'test', $c = null)
{
echo "a is $a'n";
echo "b is $b'n";
echo "c is $c'n";
}
现在你可以这样做了:
test(1, 'foo', 'bar');
你会得到:
a is 1
b is foo
c is bar
或者这个:
test(37);
你会得到:
a is 37
b is test
c is