PHP Closure类
介绍
匿名函数(也称为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
}方法
privateClosure::__construct(void)—此方法仅存在于不允许实例化Closure类的情况。此类的对象由匿名函数创建。
公共静态Closure::bind(Closure$closure,object$newthis[,mixed$newscope=“static”])-Closure—复制具有特定绑定对象和类范围的闭包。此方法是Closure::bindTo()的静态版本。
公共Closure::bindTo(object$newthis[,mixed$newscope=“static”])-Closure—使用新的绑定对象和类范围复制闭包。创建并返回具有相同主体和绑定变量,但具有不同对象和新类作用域的新匿名函数。
publicClosure::call(object$newthis[,mixed$...])-mixed—临时将闭包绑定到newthis,并使用任何给定的参数调用它。
封闭示例
<?php
class A {
public $nm;
function __construct($x){
$this->nm=$x;
}
}
//使用调用方法
$hello = function() {
return "Hello " . $this->nm;
};
echo $hello->call(new A("Amar")). "\n";;
//使用绑定方法
$sayhello = $hello->bindTo(new A("Amar"),'A');
echo $sayhello();
?>输出结果
上面的程序显示以下输出
Hello Amar Hello Amar