php 에서 클로저 함수에 use
사용방법
다음은 에러가 난다. 함수 밖에서 쓰고있는 $message 를 함수 안에서 쓸 수 없기 때문.
$message = 'hello';
// No "use"
$example = function () {
var_dump($message);
};
echo $example(); //undefined
하지만 다음과 같이 use
를 사용했을 경우 함수 바깥에서 쓴 변수를 함수 안에서도 사용할 수 있다
$message = 'hello';
// Inherit $message
$example = function () use ($message) {
var_dump($message);
};
echo $example(); //hello
(위 소스와 이어서) 그리고선 다음과 같이 사용하면 뭐라고 출력될까?
// Inherited variable's value is from when the function
// is defined, not when called
$message = 'world';
echo $example(); //hello
위에서 $example 클로저 함수에서 $message를 "hello"라고 입력된 것을 사용하라고 해놨기 때문에
비록 $message를 world로 바꿨을지라도 #example안에 있는 $message 변수에 값이 바뀌지 않는다.
따라서 hello 가 출력이 된다.
그렇다면 만약 $example 클로저 함수 안에 $message 값을 변경하고 싶다면 어떻게 해야할까?
// Reset message
$message = 'hello';
// Inherit by-reference
$example = function () use (&$message) {
var_dump($message);
};
echo $example(); //hello
// The changed value in the parent scope
// is reflected inside the function call
$message = 'world';
echo $example(); //world
위와같이 $example 함수에 $message 변수를 use 할 때 &$message 로 사용하면
$exmple에 있는 $message 값이 변경된다.