2023-08-19

PHP闭包类

PHP闭包类

介绍

匿名函数(也称为lambda)返回Closure类的对象。这个类有一些额外的方法,可以进一步控制匿名函数。

语法

Closure {
   /* Methods */
   private __construct ( void )
   public static bind ( Closure $closure , object $newthis [, mixed $newscope = "static" ] ) : Closure
   public bindTo ( object $newthis [, mixed $newscope = "static" ] ) : Closure
   public call ( object $newthis [, mixed $... ] ) : mixed
   public static fromCallable ( callable $callable ) : Closure
}
登录后复制

方法

private Closure::__construct ( void ) — 此方法仅用于禁止实例化Closure类。此类的对象由匿名函数创建。

public static Closure::bind ( Closure $closure , object $newthis [, mixed $newscope = "static" ] ) − Closure — 使用特定绑定对象和类作用域复制闭包。此方法是Closure::bindTo()的静态版本。

public Closure::bindTo ( object $newthis [, mixed $newscope = "static" ] ) − Closure — 使用新的绑定对象和类作用域复制闭包。创建并返回一个具有相同主体和绑定变量,但具有不同对象和新类作用域的新匿名函数。

public Closure::call ( object $newthis [, mixed $… ] ) − mixed — 将闭包临时绑定到newthis,并使用任何给定的参数调用它。

闭包示例

在线演示

<?php
class A {
   public $nm;
   function __construct($x){
      $this->nm=$x;
   }
}
// Using call method
$hello = function() {
   return "Hello " . $this->nm;
};
echo $hello->call(new A("Amar")). "";;
// using bind method
$sayhello = $hello->bindTo(new A("Amar"),'A');
echo $sayhello();
?>
登录后复制

输出

上述程序显示以下输出

Hello Amar
Hello Amar
登录后复制

以上就是PHP闭包类的详细内容,更多请关注php中文网其它相关文章!

https://www.php.cn/faq/593515.html

发表回复

Your email address will not be published. Required fields are marked *