개요
PHP에서 익명 함수(Anonymous Function), 즉 람다(lambda) 함수를 생성하면 그 결과로 Closure 클래스의 객체가 반환됩니다. Closure 클래스 자체는 단순한 내부 클래스처럼 보이지만, 익명 함수를 더 세밀하게 제어할 수 있는 유용한 메서드들을 제공합니다.
이 글에서는 Closure 클래스의 구조와 주요 메서드인 bind(), bindTo(), call() 등의 사용법을 예제와 함께 살펴보겠습니다.
Closure 클래스 문법
Closure {
/* Methods */
private __construct ( void )
public static bind ( Closure $closure , object $newthis [, mixed $newscope = "static" ] ) : Closure
public bindTo ( object $newthis [, mixed $newscope = "static" ] ) : Closure
public call ( object $newthis [, mixed $... ] ) : mixed
public static fromCallable ( callable $callable ) : Closure
}주요 메서드 설명
1. private Closure::__construct ( void )
Closure 클래스의 인스턴스를 직접 생성하는 것을 막기 위해서만 존재하는 생성자입니다. 이 클래스의 객체는 오직 익명 함수를 통해서만 만들어집니다.
2. public static Closure::bind ( Closure $closure , object $newthis [, mixed $newscope = "static" ] ) : Closure
특정 객체와 클래스 스코프(class scope)에 바인딩된 클로저의 복사본을 반환하는 정적(static) 메서드입니다. Closure::bindTo()의 정적 버전이라고 생각하면 됩니다.
3. public Closure::bindTo ( object $newthis [, mixed $newscope = "static" ] ) : Closure
클로저를 새로운 객체와 새로운 클래스 스코프에 바인딩하여 복사본을 생성하고 반환합니다. 본문과 바인딩된 변수는 동일하지만, 다른 객체와 새로운 클래스 스코프를 갖는 새로운 익명 함수가 만들어집니다.
4. public Closure::call ( object $newthis [, mixed $... ] ) : mixed
클로저를 일시적으로 $newthis 객체에 바인딩한 뒤, 전달된 매개변수와 함께 즉시 호출합니다. 호출 후에는 원래의 바인딩 상태가 유지됩니다.
Closure 활용 예제
아래 예제는 call() 메서드와 bindTo() 메서드를 사용해 클로저 내부에서 객체의 프로퍼티에 접근하는 방법을 보여줍니다.
<?php
class A {
public $nm;
function __construct($x){
$this->nm=$x;
}
}
// call() 메서드 사용
$hello = function() {
return "Hello " . $this->nm;
};
echo $hello->call(new A("Amar")). "
";
// bindTo() 메서드 사용
$sayhello = $hello->bindTo(new A("Amar"),'A');
echo $sayhello();
?>실행 결과
위 프로그램을 실행하면 다음과 같은 출력이 나타납니다.
Hello Amar Hello Amar
정리
Closure 클래스는 PHP의 익명 함수를 강력하게 확장해 주는 도구입니다. 특히 bindTo()나 call()을 활용하면 클로저가 특정 객체의 컨텍스트에서 동작하도록 만들 수 있어, 콜백 처리나 의존성 주입 같은 고급 패턴을 구현할 때 매우 유용합니다.