PHP根据参数返回函数的不同部分

时间:2015-11-04 20:14:03

标签: php function parameters

有没有办法根据()中传递的内容返回函数的一部分?举个例子:

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

otherDate:

test($wo, otherDate);

返回:

10/01/2015

正常输出:

test($wo);

返回:

12/01/2015

2 个答案:

答案 0 :(得分:2)

传递一个指定返回内容的参数:

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);  

答案 1 :(得分:0)

你的问题很模糊,但如果我理解正确,你需要可选的参数。您可以通过在函数定义中为它们提供默认值来使函数参数可选:

// $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