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.| CARVIEW |
Select Language
HTTP/2 301
server: myracloud
date: Sat, 27 Dec 2025 02:24:44 GMT
content-type: text/html
content-length: 161
location: https://www.php.net/manual/es/class.closure.php
HTTP/2 200
server: myracloud
date: Sat, 27 Dec 2025 02:24:45 GMT
content-type: text/html; charset=utf-8
content-language: en
permissions-policy: interest-cohort=()
x-frame-options: SAMEORIGIN
link: ; rel=shorturl
last-modified: Sat, 27 Dec 2025 02:11:52 GMT
vary: accept-encoding
content-encoding: gzip
expires: Sat, 27 Dec 2025 02:24:45 GMT
cache-control: max-age=0
PHP: Closure - Manual
update page now
La clase Closure
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
Introducción
Clase utilizada para representar las funciones anónimas.
Las funciones anónimas producen objetos de este tipo. Esta clase tiene métodos que permiten un control adicional de la función anónima después de su creación.
Además de los métodos especificados aquí, esta clase también posee un método
__invoke. Esto es por razones de lógica con la implementación de
el método mágico de llamada.
Sinopsis de la Clase
Historial de cambios
| Versión | Descripción |
|---|---|
| 8.4.0 | La salida de Closure::__debugInfo() incluye ahora el nombre, la línea y el fichero del cierre. |
Tabla de contenidos
- Closure::__construct — Constructor que anula la instanciación
- Closure::bind — Duplicar un cierre con un objeto vinculado y ámbito de clase especificados
- Closure::bindTo — Duplica la cierre con un nuevo objeto vinculado y un nuevo contexto de clase.
- Closure::call — Vincula y llama al cierre
- Closure::fromCallable — Convierte un 'callable' en un cierre
+add a note
User Contributed Notes 4 notes
chuck at bajax dot us ¶
10 years ago
joe dot scylla at gmail dot com ¶
9 years ago
Small little trick. You can use a closures in itself via reference.
Example to delete a directory with all subdirectories and files:
<?php
$deleteDirectory = 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);
}
}
}
closedir($resource);
rmdir($path);
};
$deleteDirectory("path/to/directoy");
?>
luk4z_7 at hotmail dot com ¶
10 years ago
Scope
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.
info at ensostudio dot ru ¶
3 years ago
compare closures:
<?php
(string) new ReflectionFunction($fn) === (string) new ReflectionFunction($fn2)
?>
↑ and ↓ to navigate •
Enter to select •
Esc to close • / to open
Press Enter without
selection to search using Google