아래의 두 가지 기술은 모두 제대로 작동하는 것 같습니다. 나는 어떤 기술이 가장 적절한 기술인지 알고 싶다.한 함수에서 후속 함수로 배열 변수를 전달하는 올바른 방법은 무엇입니까
// 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는 오류 메시지를 표시하지 않습니다. 더 나은 될 수있다 그것은이 코드의 목적이 무엇인지 질문에서 명확하지 않다
$error_arr = [
'step_one' => step_one($text_str),
'step_two' => step_two($text_str),
];
, 그래서 어떤 방법 또는 기타 :
두 가지 방법 모두 완전히 틀립니다! 'global'을 사용하지 마십시오! 못! 필요한 경우 해당 배열을 참조 인수 ('& $ error_arr')로 넘겨 줄 수 있습니다. 그러나 예외를 사용하는 것이 훨씬 더 좋습니다. – arkascha
변수 이름을 $ error_arr로 지정했기 때문에 PHP는 오류를 발생시키지 않습니다. PHP에서 하드 오류를 발생 시키려면 "Exception"클래스 (http://php.net/manual/en/class.exception.php)를 사용하십시오. 두 가지 예가 모두 불쾌하고 전 세계를 피할 것입니다. 특히 첫 번째 예 (변수로 선언 할 때와 동일한 변수를 전달, 아야). – IncredibleHat
@arkascha 정보를 제공해 주셔서 감사합니다. (& $ error_arr) 작동하는 것 같습니다. 오늘 그 일찍 시도하고 오류 메시지가 나타납니다. 필자는 기능면에서 세계적인 수준에 이르렀으며 여전히 효과가 있다고 생각합니다. :) – Harvey