php教程

Closure 类

(PHP 5 >= 5.3.0, PHP 7)

简介

用于代表 匿名函数 的类.

匿名函数(在 PHP 5.3 中被引入)会产生这个类型的对象。在过去,这个类被认为是一个实现细节,但现在可以依赖它做一些事情。自 PHP 5.4 起,这个类带有一些方法,允许在匿名函数创建后对其进行更多的控制。

除了此处列出的方法,还有一个 __invoke 方法。这是为了与其他实现了 __invoke()魔术方法 的对象保持一致性,但调用匿名函数的过程与它无关。

类摘要

Closure {
/* 方法 */
__construct ( void )
public static bind ( Closure $closure , object $newthis [, mixed $newscope = 'static' ] ) : Closure
public bindTo ( object $newthis [, mixed $newscope = 'static' ] ) : Closure
}

Table of Contents

User Contributed Notes

joe dot scylla at gmail dot com 08-Apr-2016 08:46
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 14-Jun-2015 05:42
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.
chuck at bajax dot us 09-Jun-2015 04:16
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.

CopyRight © 2008-2022 verySource.Com All Rights reserved. 京ICP备17048824号-1 京公网安备:11010502034788