2012-04-20 38 views
2

我在命名函數時遇到了問題。我有一個課,我需要2個功能,如下所示。PHP類函數命名

class myclass { 
    public function tempclass() { 
     echo "default"; 
    } 
    public function tempclass ($text) { 
     echo $text; 
    } 
} 

當我打電話

tempclass('testing'); // (called after creating the object) 

function tempclass()被稱爲我怎麼能有2個功能具有相同名稱但不同的參數?

+0

爲什麼使用報價格式,而不是代碼格式化您的代碼? – ThiefMaster 2012-04-20 15:21:38

+0

@ThiefMaster哎呀,我的壞。 – 2012-04-20 15:34:48

回答

5

傳統的重載目前在PHP中不可行。相反,您需要檢查傳遞的參數,並確定您希望如何回覆。

此時退房func_num_argsfunc_get_args。您可以在內部使用這兩種方法來確定如何響應某些方法的調用。例如,你的情況,你可以做到以下幾點:

public function tempclass() { 
    switch (func_num_args()) { 
    case 0: 
     /* Do something */ 
     break; 
    case 1: 
     /* Do something else */ 
    } 
} 

或者,你可以爲你的論點提供默認值,以及,並利用這些來確定如何你應該作出反應:

public function tempclass ($text = false) { 
    if ($text) { 
    /* This method was provided with text */ 
    } else { 
    /* This method was not invoked with text */ 
    } 
} 
+1

+1,但建議編輯您的答案以包含對'func_get_args()'和'func_num_args()'的引用鏈接。 :-) – FtDRbwLXw6 2012-04-20 15:25:15

+0

很感謝。 – 2012-04-20 15:37:53

0

PHP中無法重載。

但是,對於您的上面簡單的例子,像這樣的工作:

class myclass { 
    public function tempclass ($text='Default') { 
     echo $text; 
    } 
} 
+0

作出了我認爲您可能同意的更改。 – 2012-04-20 15:28:36

+0

完全!甚至沒有想到=) – Nick 2012-04-20 15:33:21

+0

你的在線聯繫表格不起作用。你住在蘇格蘭,我也是。我的聯繫方式可以通過這個視線獲得。 – 2012-04-20 15:46:37