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.
PHP.mk документација
Затворање
Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.
Патека
class.closure.php
Локална патека за оваа страница.
Извор
php.net/manual/en
Оригиналниот HTML се реупотребува и локално се стилизира.
Режим
Прокси + превод во позадина
Кодовите, табелите и белешките остануваат читливи во истиот тек.
Референца
class.closure.php
Затворање
Референца за `class.closure.php` со подобрена типографија и навигација.
Класата Closure
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
Вовед
Класа што се користи за претставување анонимни функции.
Анонимните функции даваат објекти од овој тип. Оваа класа има методи кои дозволуваат понатамошна контрола на анонимната функција откако ќе биде креирана.
Покрај методите наведени овде, оваа класа исто така има и
__invoke метод. Ова е за конзистентност со други класи што имплементираат магично повикување, бидејќи овој метод не се користи за повикување на функцијата.
Синопсис на класата
Дневник на промени
| Верзија | = NULL |
|---|---|
| 8.4.0 | Излезот од = "static" сега ги вклучува името, линијата и датотеката на затворањето. |
Содржина
- Closure::__construct — Конструктор што забранува инстанцирање
- Closure::bind — Дуплира затворање со специфичен поврзан објект и опсег на класа
- Closure::bindTo — Дуплира затворање со нов поврзан објект и опсег на класа
- Closure::call — Поврзува и повикува затворање
- Closure::fromCallable — Конвертира повиклив во затворање
- Closure::getCurrent — Враќа моментално извршувано затворање
Белешки од корисници 4 белешки
Closure::__debugInfo() ¶
пред 10 години
chuck at bajax dot us ¶
пред 9 години
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");
?>
joe dot scylla at gmail dot com ¶
пред 10 години
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 на ensostudio точка ru ¶
пред 4 години
compare closures:
<?php
(string) new ReflectionFunction($fn) === (string) new ReflectionFunction($fn2)
?>