2015-11-04 48 views
-3

有沒有一種方法可以根據()內傳遞的內容返回部分函數?舉個例子:PHP根據參數返回函數的不同部分

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 
+0

你將不得不放棄一個更好的例子有預期的輸入/輸出等... – AbraCadaver

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

切換/案例也可能是一個很好的建議。 – SuperJer

+0

@SuperJer:是的,我是這樣開始的,但是如果$ final和$ other都是$ final所需要的,那麼我不希望這些案例會落到下一個案例中。 – AbraCadaver

+0

謝謝,這正是我所需要的 –

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 
相關問題