首页 » SEO优化 » php返回fail技巧_Closure匿名函数和Closure类

php返回fail技巧_Closure匿名函数和Closure类

访客 2024-12-07 0

扫一扫用手机浏览

文章目录 [+]

Closure, 匿名函数, 又称为Anonymous functions, 是php5.3的时候引入的。
匿名函数便是没有定义名字的函数, 许可临时创建一个没有指定名称的函数, 最常常用作回调函数(callback)参数的值。

Closure 关键字浸染:用于限定通报的参数必须是匿名函数

php返回fail技巧_Closure匿名函数和Closure类

<?phpfunction test() { return 100;};function testClosure(Closure $callback){ return $callback();}$a = testClosure(test());print_r($a);?>/Catchable fatal error: Argument 1 passed to testClosure() must be an instance of Closure, integer given, called in D:\WWW\test\test23.php on line 11 and defined in D:\WWW\test\test23.php on line 6/

涌现缺点的缘故原由testClosure()通报额参数不是匿名函数, 以是涌现以上缺点信息。

php返回fail技巧_Closure匿名函数和Closure类
(图片来自网络侵删)

<?php$f = function () {return 100;};function testClosure(Closure $callback){ return $callback();}$a = testClosure($f);print_r($a); //100?>

如果要调用一个类里面的匿名函数呢?

class C { public static function testC() { return function($i) { return $i+100; }; }}function testClosure(Closure $callback){ return $callback(13);}$a = testClosure(C::testC());print_r($a); //113

Closure 类

用于代表匿名函数的类

Closure {/ 方法 /__construct ( void )public static Closure bind ( Closure $closure , object $newthis [, mixed $newscope = 'static' ] )public Closure bindTo ( object $newthis [, mixed $newscope = 'static' ] )}

Closure::__construct 用于禁止实例化的布局函数。

Closure::bind 复制一个闭包, 绑定指定的$this工具和类浸染域。

public static Closure Closure::bind ( Closure $closure , object $newthis [, mixed $newscope = 'static' ] )

closure 须要绑定的匿名函数。

newthis 须要绑定到匿名函数的工具, 或者 NULL 创建未绑定的闭包。

newscope 想要绑定给闭包的类浸染域, 或者 'static' 表示不改变。
如果传入一个工具, 则利用这个工具的类型名。
类浸染域用来决定在闭包中$this 工具的私有、保护方法的可见性。

返回值

返回一个新的 Closure 工具 或者在失落败时返回 FALSE

<?phpclass A { private static $sfoo = 1 ; private $ifoo = 2 ;}$cl1 = static function() {return A :: $sfoo ;};$cl2 = function() {return $this -> ifoo ;};$bcl1 = Closure :: bind ( $cl1 , null , 'A' );$bcl2 = Closure :: bind ( $cl2 , new A (), 'A' );echo $bcl1 (), "\n" ; //1echo $bcl2 (), "\n" ; //2?>

Closure::bindTo 复制当前闭包工具, 绑定指定的$this工具和类浸染域。

public Closure Closure::bindTo ( object $newthis [, mixed $newscope = 'static' ] )

参数

newthis 绑定给匿名函数的一个工具, 或者 NULL 来取消绑定。

newscope 关联到匿名函数的类浸染域, 或者 'static' 保持当前状态。
如果是一个工具, 则利用这个工具的类型为心得类浸染域。
这会决定绑定的工具的保护、私有成员方法的可见性。

返回值

返回新创建的 Closure 工具 或者在失落败时返回 FALSE

<?phpclass A { function __construct ( $val ) { $this -> val = $val ; } function getClosure () { //returns closure bound to this object and scope return function() { return $this -> val ; };}}$ob1 = new A ( 1 );$ob2 = new A ( 2 );$cl = $ob1 -> getClosure ();echo $cl (), "\n" ; //1$cl = $cl -> bindTo ( $ob2 );echo $cl (), "\n" ; //2?>

标签:

相关文章

php数组全分列技巧_PHP 数组排序

PHP - 数组排序函数在本章中,我们将逐一先容下列 PHP 数组排序函数:sort( - 对数组进行升序排列rsort( -...

SEO优化 2024-12-09 阅读0 评论0