Класс 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" ] )
}

Содержание

  • Closure::__construct — Конструктор запрещающий создавать новые объекты
  • Closure::bind — Дублирует замыкание с указанием связанного объекта и области видимости класса
  • Closure::bindTo — Дублирует замыкание с указанием связанного объекта и области видимости класса

Коментарии

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.
2015-06-09 19:16:46
http://php5.kiev.ua/manual/ru/class.closure.html
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.
2015-06-14 20:42:53
http://php5.kiev.ua/manual/ru/class.closure.html
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");
?>
2016-04-08 11:46:54
http://php5.kiev.ua/manual/ru/class.closure.html
compare closures:
<?php 
(string) new ReflectionFunction($fn) === (string) new ReflectionFunction($fn2)
?>
2022-03-21 19:41:06
http://php5.kiev.ua/manual/ru/class.closure.html

    Поддержать сайт на родительском проекте КГБ