PHP Closure 类
phpserver side programmingprogramming更新于 2025/7/18 11:22:17
简介
匿名函数(也称为 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 [, mix $newscope = "static" ] ) − Closure — 使用特定的绑定对象和类作用域复制闭包。此方法是 Closure::bindTo() 的静态版本。
public Closure::bindTo ( object $newthis [, mix $newscope = "static" ] ) − Closure — 使用新的绑定对象和类作用域复制闭包。创建并返回一个新的匿名函数,其函数体和绑定变量相同,但对象不同,且具有新的类作用域。
public Closure::call ( object $newthis [, mixed $... ] ) − mix — 临时将闭包绑定到 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

