2017-10-18 2 views
0

아래의 두 가지 기술은 모두 제대로 작동하는 것 같습니다. 나는 어떤 기술이 가장 적절한 기술인지 알고 싶다.한 함수에서 후속 함수로 배열 변수를 전달하는 올바른 방법은 무엇입니까

// 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), 
]; 

, 그래서 어떤 방법 또는 기타 :

+2

두 가지 방법 모두 완전히 틀립니다! 'global'을 사용하지 마십시오! 못! 필요한 경우 해당 배열을 참조 인수 ('& $ error_arr')로 넘겨 줄 수 있습니다. 그러나 예외를 사용하는 것이 훨씬 더 좋습니다. – arkascha

+0

변수 이름을 $ error_arr로 지정했기 때문에 PHP는 오류를 발생시키지 않습니다. PHP에서 하드 오류를 발생 시키려면 "Exception"클래스 (http://php.net/manual/en/class.exception.php)를 사용하십시오. 두 가지 예가 모두 불쾌하고 전 세계를 피할 것입니다. 특히 첫 번째 예 (변수로 선언 할 때와 동일한 변수를 전달, 아야). – IncredibleHat

+0

@arkascha 정보를 제공해 주셔서 감사합니다. (& $ error_arr) 작동하는 것 같습니다. 오늘 그 일찍 시도하고 오류 메시지가 나타납니다. 필자는 기능면에서 세계적인 수준에 이르렀으며 여전히 효과가 있다고 생각합니다. :) – Harvey

답변

0

당신이 뭔가를 할 수 있습니다. 예를 들어, 당신은 그냥이 특정 장소에 여러 단계의 $text_str를 처리해야하는 경우 - 대신 클로저를 사용할 수 있습니다 : 당신은 몇 가지 변수를 공유하는이 기능을 원하는 경우

$processing = [ 
    'step_one' => function($str) { /* some code */ return true }, 
    'step_two' => function($str) { /* some code */ return true }, 
]; 
$results = []; 
foreach($processing as $func) { 
    array_push($results, $func($text_str)); 
} 

- 당신이 use 절을 통해 그것을 전달할 수 있습니다

$shared = []; 
$processing = [ 
    'step_one' => function($str) use ($shared) { /* some code */ return true }, 
    'step_two' => function($str) use ($shared) { /* some code */ return true }, 
]; 
$results = []; 
foreach($processing as $func) { 
    array_push($results, $func($text_str)); 
} 
0

두 기술은 실제로 동일한 기술입니다. 여기

이 예제 :

$error_arr = ['example' => 'value']; 

$not_error_arr = ['something' => 'else']; 

function step_one($text_str, $error_arr) { 
    global $error_arr; 
    $error_arr['step_one'] = true; 
} 

step_one('foo', $not_error_arr); 

var_dump($error_arr, $not_error_arr); 

이 출력 할 것이다

어레이 (크기 = 2) '예'=> 문자열 '값'(길이 = 5) 'step_one'=> 부울 사실

배열 (크기 = 1) '뭔가'=> 문자열 '다른 사람'(길이 = 4)

매개 변수으로 전달한 배열에 'step_one'값이 이 지정되어 있지 않습니다.이 할당은 global $error_arr에 의해 재정의되었으므로

그래서 관계없이

function step_one($text_str,$error_arr) {... 

에 두 번째 인수로 전달할 어떤 함수 내 글로벌 정의는 무시됩니다 것을 의미합니다. 전역 범위의 변수가 매개 변수로 전달한 것과 동일하기 때문에 작성하는 것처럼 보입니다.

관련 문제