2014-06-16 53 views
0

和我做了一個自定義的PHP函數,如下所示:使它所以所有的變量沒有被定義,當一個功能,我使用的000webhost被稱爲

function example($test1, $test2, $test3) { 
    echo $test1 . $test2 . $test3; 
} 

然後我做example('hello');和它說:

PHP Error Message 

Warning: Missing argument 2 for example(), called in /home/a8525001/public_html/test.php on line 5 and defined in /home/a8525001/public_html/test.php on line 2 

Free Web Hosting 

PHP Error Message 

Warning: Missing argument 3 for example(), called in /home/a8525001/public_html/test.php on line 5 and defined in /home/a8525001/public_html/test.php on line 2 

Free Web Hosting 
1 

有什麼辦法可以阻止這些警告,而無需訪問服務器的php.ini?同樣的代碼工作我的XAMPP服務器上的微細...提前

感謝,

+0

您是否在文件頂部嘗試了error_reporting(0)? – sinisake

+0

@nevermind我不認爲這是最好的主意,因爲那樣我看不到其他錯誤...我找到了解決方案並將其發佈到下面。感謝您的建議:) – Speedysnail6

回答

1

您有幾種選擇,這裏是他們的2:

您可以使用下面的設置爲null時(有他們的定義)。

function example($test = NULL, $test2 = NULL, test3 = NULL) { 
    // use variables here but do something like this to check it isn't empty 
    if($test !== NULL) { 
     echo $test; 
    } 
    /// etc...and use the rest in whatever you need 
} 

或者你可以使用func_get_args(),它允許你去是這樣的:

function example() { 
    $args = func_get_args(); 
    foreach($args as $i => $arg) { 
     echo "Argument {$i} is: {$arg} <br />"; 
    } 
} 

允許你做這樣的事情:

example('derp', 'derp1', 'derp2'); 

和上面的函數將返回:

Argument 0 is: derp 
Argument 1 is: derp1 
Argument 2 is: derp2 

可選:您可以使用func_num_args()來確保在函數中設置了參數。

+0

謝謝!我想我會做NULL選項。這似乎更容易。第二種方法比第一種方法有什麼優勢? – Speedysnail6

+0

@ Speedysnail6第二個選項允許您使用盡可能多的參數,而不必像每個例子那樣指定它們:'example($ test,$ test2,$ test3)' – Darren

+0

啊好吧!謝謝! – Speedysnail6

0

就得到了答案:d,

要在可選功能的變量,定義它在代碼本身如:

function example($test1, $test2 = NULL, $test3 = NULL) { 
    echo $test1 . $test2 . $test3; 
} 

然後,這些值將已經定義,但當功能被調用時,如果可選的值被定義,它會overri NULL。

來源:PHP function missing argument error

相關問題