La clase Closure

(PHP 5 >= 5.3.0)


Clase empleada para representar funciones anónimas.

Las funciones anónimas, implementadas en PHP 5.3, producían objetos de este tipo. Este hecho solía ser considerado como un detalle de implementación, pero ahora puede confiarse en él. Desde PHP 5.4, esta clase tiene métodos que permiten más control de las funciones anónimas después de que hayan sido creadas.

Además de los métodos listados aquí, esta clase también posse un método __invoke. Esto es por consistencia con otras clases que implementan la llamada mágica, ya que este método no se usa para llamar a la función.

Sinopsis de la Clase

Closure {
/* Métodos */
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 $... ] )

Tabla de contenidos

add a note add a note

User Contributed Notes 2 notes

chuck at bajax dot us
5 months 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.
luk4z_7 at hotmail dot com
5 months 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