Php 简明教程

PHP – Closure::call()

在 PHP 中, closure 是一个匿名函数,可以访问其创建的范围内的变量,即使该范围已经关闭。你需要在其中指定 use 关键字。

In PHP, a closure is an anonymous function that has access to the variables in the scope in which it was created, even after that scope has closed. You need to specify use keyword in it.

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

Closures are objects that encapsulate the function code and the scope in which they were created. With PHP 7, a new closure::call() method was introduced to bind an object scope to a closure and invoke it.

Methods in the Closure Class

闭包类具有以下方法,包括 call() 方法 −

The Closure class has the following methods including the call() method −

final class Closure {

   /* Methods */
   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() method 是闭包类的静态方法。它被引入为 bind() 或 bindTo() 方法的快捷方式。

The call() method is a static method of Closure class. It has been introduced as a shortcut the bind() or bindTo() methods.

bind() method 根据特定的 bound 对象和类范围复制闭包,而 bindTo() 方法则使用新的 bound 对象和类范围复制闭包。

The bind() method Duplicates a closure with a specific bound object and class scope while the bindTo() method duplicates the closure with a new bound object and class scope.

call() 方法具有以下 signature

The call() method has the following signature

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

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

The call() method temporarily binds the closure to newThis, and calls it with any given parameters.

在 PHP 7 之前的版本中,bindTo() 方法可以使用如下方式:

With version prior to PHP 7, the bindTo() method can be used as follows −

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

   // Define a closure Pre PHP 7 code
   $getValue = function() {
      return $this->x;
   };

   // Bind a clousure
   $value = $getValue->bindTo(new A, 'A');
   print($value());
?>

该程序将 $getValue (它是一个闭包对象)绑定到 A 类的对象,并打印其私有变量 $x 的值 - 它为 1。

The program binds the $getValue which is a closure object, to the object of A class and prints the value of its private variable $x – it is 1.

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

With PHP 7, the binding is achieved by call() method as shown below −

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

   // PHP 7+ code, Define
   $value = function() {
      return $this->x;
   };

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