Closure 클래스

(PHP 5 >= 5.3.0, PHP 7)


익명 함수를 만들기 위해 사용되는 클래스 입니다.

PHP 5.3 에서 구현된 익명함수는 이 타입의 객체로 대체 되었습니다. 이 때문에 늘 구현 상세를 고려해야 했습니다. 하지만 이제 그러지 않아도 됩니다. PHP 5.4 부터 이 클래스는 객체가 만들어진 이후부터 익명함수를 조금더 제어 할수 있는 메서드를 가지게 되었습니다.

여기에 나열된 메서드 이외에, 이 클래스는 __invoke 메서드를 가집니다. 이것은 매직콜을 구현한 다른 클래스들과의 일관성을 위한것이며, 함수를 호출하기 위해 사용되지는 않습니다.

클래스 개요

Closure {
/* 메소드 */
private __construct ( void )
public static Closure bind ( Closure $closure , object $newthis [, mixed $newscope = "static" ] )
public Closure bindTo ( object $newthis [, mixed $newscope = "static" ] )
public mixed call ( object $newthis [, mixed $... ] )

Table of Contents

add a note add a note

User Contributed Notes 3 notes

chuck at bajax dot us
7 years ago
This caused me some confusion a while back when I was still learning what closures were and how to use them, but what is referred to as a closure in PHP isn't the same thing as what they call closures in other languages (E.G. JavaScript).

In JavaScript, a closure can be thought of as a scope, when you define a function, it silently inherits the scope it's defined in, which is called its closure, and it retains that no matter where it's used.  It's possible for multiple functions to share the same closure, and they can have access to multiple closures as long as they are within their accessible scope.

In PHP,  a closure is a callable class, to which you've bound your parameters manually.

It's a slight distinction but one I feel bears mentioning.
joe dot scylla at gmail dot com
6 years ago
Small little trick. You can use a closures in itself via reference.

Example to delete a directory with all subdirectories and files:

= null;
$deleteDirectory = function($path) use (&$deleteDirectory) {
$resource = opendir($path);
    while ((
$item = readdir($resource)) !== false) {
        if (
$item !== "." && $item !== "..") {
            if (
is_dir($path . "/" . $item)) {
$deleteDirectory($path . "/" . $item);
            } else {
unlink($path . "/" . $item);
luk4z_7 at hotmail dot com
7 years ago
A closure encapsulates its scope, meaning that it has no access to the scope in which it is defined or executed. It is, however, possible to inherit variables from the parent scope (where the closure is defined) into the closure with the use keyword:

function createGreeter($who) {
              return function() use ($who) {
                  echo "Hello $who";

$greeter = createGreeter("World");
$greeter(); // Hello World

This inherits the variables by-value, that is, a copy is made available inside the closure using its original name.
font: Zend Certification Study Guide.
To Top