以下兩種技術似乎都可以正常工作。我只想知道哪種技術是最合適的技術。將數組變量從一個函數傳遞到後續函數的正確方法是什麼
// parameters
$text_str = 'antique picture';
$error_arr = array();
的$error_arr
變量被包括在參數:從參數省略
function step_one($text_str,$error_arr) {
global $error_arr;
//... some code goes here ...
$error_arr['step_one'] = true;
}
function step_two($text_str,$error_arr) {
global $error_arr;
//... some code goes here ...
$error_arr['step_two'] = true;
}
// call the two functions that have $error_arr included in the parameters
step_one($test_str,$error_arr);
step_two($text_str,$error_arr);
// they output the following
print_r outputs array('step_one' => 1)
print_r outputs array('step_one' => 1, 'step_two' => 1)
的$error_arr
變量。
function step_one($text_str) {
global $error_arr;
//... some code goes here ...
$error_arr['step_one'] = true;
}
function step_two($text_str) {
global $error_arr;
//... some code goes here ...
$error_arr['step_two'] = true;
}
// call the functions that have the $error_arr variable omitted from the parameters
step_one($text_str);
step_two($text_str);
// the last two functions have exactly the same output as the
// first two functions even though the `$error_arr` is not included
// in the parameters
print_r outputs array('step_one' => 1)
print_r outputs array('step_one' => 1, 'step_two' => 1)
我在共享主機上運行PHP 7.1。我在控制面板中打開了display_errors
。
如果我在參數中包含$error_arr
變量或者如果使用從參數中省略$error_arr
變量的函數,PHP不會拋出任何錯誤消息。
兩種方法都是徹底_wrong_!不要使用'global'!決不!如果必須的話,您可以將該數組作爲參考參數('&$ error_arr')移交。但更好的是使用例外。 – arkascha
PHP不會拋出任何錯誤,因爲您將變量命名爲$ error_arr。如果您希望PHP發出嚴重錯誤,請使用「Exception」類(http://php.net/manual/en/class.exception.php)。你的兩個例子都是令人討厭的,我會避免使用全局變量。特別是第一個例子(在聲明變量時傳入相同的變量,ouch)。 – IncredibleHat
@arkascha感謝您的信息。 (&$ error_arr)似乎正在工作。我今天早些時候嘗試過,並收到錯誤消息。我在我的職能上評論過全球,並且仍在運作。 :) – Harvey