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

PHP returning different parts of a function based on arguments

有没有办法根据在 () 中传递的内容来 return 仅部分函数?例如:

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

Returns:

1/1/2015

其他日期:

test($wo, otherDate);

Returns:

10/01/2015

正常输出:

test($wo);

Returns:

12/01/2015

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

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

传递指定内容的参数 return:

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