PHP – Closure::call()


 PHP 闭包(Closure)是一个匿名函数,可以访问创建它的作用域中的变量,即使在该作用域关闭之后也是如此。您需要在其中指定 use 关键字。

闭包(Closure)是封装函数代码和创建它们的作用域的对象。在 PHP 7 中,引入了一个新的 closure::call() 方法,用于将对象作用域绑定到 Closure 并调用它。

Closure 类的方法

Closure 类具有以下方法,包括 call() 方法 -


final class Closure {

   /* 方法 */
   private __construct()
   public static bind(Closure $closure, ?object $newThis, object|string|null $newScope = "static"): ?Closure
   public bindTo(?object $newThis, object|string|null $newScope = "static"): ?Closure
   public call(object $newThis, mixed ...$args): mixed
   public static fromCallable(callable $callback): Closure
   
}

call() 方法是 Closure 类的静态方法。它已作为 bind() 或 bindTo() 方法的快捷方式引入。

bind() 方法复制具有特定绑定对象和类范围的闭包,而 bindTo() 方法复制具有新绑定对象和类范围的闭包。

call() 方法具有以下签名 -


public Closure::call(object $newThis, mixed ...$args): mixed

call() 方法临时将闭包绑定到 newThis,并使用任何给定的参数调用它。

对于 PHP 7 之前的版本,可以按如下方式使用 bindTo() 方法 -


<?php
   class A {
      private $x = 1;
   }

   // 定义PHP 7之前的闭包代码
   $getValue = function() {
      return $this->x;
   };

   // 绑定一个闭包
   $value = $getValue->bindTo(new A, 'A'); 
   print($value());
?>

程序将 $getValue 绑定到 A 类的对象,并打印其私有变量的值 $x – 它是 1。

在 PHP 7 中,绑定是通过 call() 方法实现的,如下所示 -


<?php
   class A {
      private $x = 1;
   }

   // PHP 7+代码,定义
   $value = function() {
      return $this->x;
   };

   print($value->call(new A));
?>