PHP Closure::call()
在 PHP 中,closure 是一个匿名函数,它可以访问创建它时的作用域中的变量,即使该作用域已经关闭。你需要在其中指定 use 关键字。
Closures 是封装了函数代码及其创建作用域的对象。从 PHP 7 开始,引入了新的 Closure::call() 方法,用于将对象作用域绑定到 closure 并调用它。
Closure 类中的方法
Closure 类包含以下方法,包括 call() 方法 —
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() 方法 是 Closure 类的静态方法。它被引入作为 bind() 或 bindTo() 方法的快捷方式。
bind() 方法 使用特定的绑定对象和类作用域复制一个 closure,而 bindTo() 方法使用新的绑定对象和类作用域复制 closure。
call() 方法具有以下 signature —
public Closure::call(object $newThis, mixed ...$args): mixed
call() 方法临时将 closure 绑定到 newThis,并使用给定的任何参数调用它。
在 PHP 7 之前的版本中,可以按以下方式使用 bindTo() 方法 —
<?php
class A {
private $x = 1;
}
// PHP 7 之前的代码,定义一个 closure
$getValue = function() {
return $this->x;
};
// 绑定一个 closure
$value = $getValue->bindTo(new A, 'A');
print($value());
?>
该程序将 $getValue(一个 closure 对象)绑定到 A 类的对象,并打印其私有变量 $x 的值,它是 1。
在 PHP 7 中,通过以下方式使用 call() 方法实现绑定 —
<?php
class A {
private $x = 1;
}
// PHP 7+ 代码,定义
$value = function() {
return $this->x;
};
print($value->call(new A));
?>