사용자 정의 함수에서 콜백 함수를 실행하는 방법은?
사용자 정의 함수에서 콜백 함수를 실행하는 방법은?
function processText($text, $formatter) {
// 콜백 함수 실행 방법
return ___($text);
}
function addExclamation($str) {
return $str . "!";
}
echo processText("Hello", "addExclamation");
정답: B
PHP에서는 변수에 저장된 함수명을 직접 호출할 수 있습니다.
⦁ 콜백 실행 방법들:
⦁
$formatter($text)
: 직접 호출 (가장 간단)⦁
call_user_func($formatter, $text)
: 내장 함수 사용⦁ 둘 다 동일한 결과를 생성
⦁ 동작 원리:
1.
$formatter
변수에 "addExclamation" 문자열 저장2.
$formatter($text)
는 addExclamation($text)
호출과 동일3. 결과: "Hello!"
⦁ 실무 활용:
function processText($text, $formatter) {
return $formatter($text);
}
echo processText("Hello", "strtoupper"); // "HELLO"
echo processText("Hello", "strtolower"); // "hello"
💡 학습 팁
이 문제를 포함한 PHP 과목의 모든 문제를 순차적으로 풀어보세요. 진행상황이 자동으로 저장되어 언제든지 이어서 학습할 수 있습니다.