美文网首页
Closure for PHP

Closure for PHP

作者: cwchym | 来源:发表于2016-10-13 16:46 被阅读0次

如其名,Closure——闭包,一个在JavaScript中随处可见的概念,产生并用于(并不准确的说辞)匿名函数( Anonymous functions ),但在PHP语言中有着概念上的些许区别:

  • PHP中的闭包有其实现的类,一个表示匿名函数的类(Class used to represent anonymous functions.):
Closure {
/* Methods */
private __construct( void )
public static Closure bind( Closure $closure, object $newthis [, mixed $newscope = "static" ] )
public Closure bindTo ( object $newthis [, mixed $newscope = "static" ] )
public mixed call ( object $newthis [, mixed $...] )
}
  • JavaScript中,匿名函数内部可以调用包含它的作用域中的变量,形成闭包。但在PHP中,闭包是类似上述代码的类,需要我们手动的将其与某些特定参数进行绑定,PHP中的匿名函数要调用包含它的作用域中的变量必须在function后使用use关键字。

在类Closure中,有上述的四个方法,下面对这四个方法进行详述:

  1. private __construct(void)
    不同于PHP中的其他类中的构造函数,这个函数的存在是为了阻止实例化此类的实例,当调用此方法时会产生E_RECOVERABLE_ERROR错误。当匿名函数产生的时候,PHP会同时为其实例化一个Closure的实例。
  2. public static Closure bind( Closure $closure, object $newthis [, mixed $newscope = "static" ] )
    此方法与下述方法类似,参照下述函数的说明。
  3. public Closure bindTo ( object $newthis [, mixed $newscope = "static" ] )
    函数用于复制当前的闭包,并将其与特定的需绑定对象和作用域进行绑定。其中$newthis参数重新指定了匿名函数内部的$this变量所指定的对象,$newscope指定了某个类,其中的protectprivate参数是对此匿名函数可见的,就如同匿名函数是此指定的类中的函数。
  4. public mixed call ( object $newthis [, mixed $...] )
    调用此闭包,即此匿名函数,并在调用时将此匿名函数与特定的参数进行绑定,参数说明如上所述。

下述简单的Closure使用例子:

<?
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";
$cl = $cl->bindTo($ob2);
echo $cl(), "\n";?>

输出结果如下:

1
2

相关文章

  • php 依赖注入的理解

    PHP 依赖注入容器实现 w3c-PHP7中Closure :: call使用示例 php手册-Closure::...

  • Closure for PHP

    如其名,Closure——闭包,一个在JavaScript中随处可见的概念,产生并用于(并不准确的说辞)匿名函数(...

  • php之闭包函数(Closure)

    php闭包函数(Closure) JS闭包 js和php闭包使用和区别

  • PHP Closure类的bind()和bindTo()怎么用?

    看PHP手册关于Closure的bind和bindTo的用法。真心没看懂,不理解其中的概念。比如Closure::...

  • php中的匿名函数和闭包

    php中的匿名函数和闭包(closure) 一:匿名函数 (在php5.3.0 或以上才能使用) php中的匿名函...

  • PHP Closure 匿名类

    闭包函数特点 闭包函数不能直接访问闭包外的变量,而是通过use 关键字来调用上下文变量(闭包外的变量),也就是说通...

  • PHP anonymous function 设置为 stati

    PHP anonymous function 会被创建为 Closure 对象实例,默认情况下,会把所在对象的 $...

  • php闭包函数(Closure)

    匿名函数 提到闭包就不得不想起匿名函数,也叫闭包函数(closures),貌似PHP闭包实现主要就是靠它。声明一个...

  • PHP闭包(Closure)初探

    匿名函数 提到闭包就不得不想起匿名函数,也叫闭包函数(closures),貌似PHP闭包实现主要就是靠它。声明一个...

  • PHP闭包的理解是使用

    PHP 闭包函数及Closure对象的总结 PHP的闭包 其实学习一个新的概念,除了知道怎么使用,更多的我是想知道...

网友评论

      本文标题:Closure for PHP

      本文链接:https://www.haomeiwen.com/subject/olbwyttx.html