开发学院

您的位置:首页>教程>正文

教程正文

PHP 7 Closure::call()

PHP 7 Closure::call()

  Closure::call()方法被添加作为临时绑定的对象范围,以封闭并简便调用它的方法。它的性能相比PHP5.6 bindTo要快得多

例子:PHP 7以前的版本

<?php
   class A {
      private $x = 1;
   }

   // Define a closure Pre PHP 7 code
   $getValue = function() {
      return $this->x;
   };

   // Bind a clousure
   $value = $getValue->bindTo(new A, 'A'); 

   print($value());
?>

  上述代码的输出如下:

1

例子:PHP 7版本

<?php
   class A {
      private $x = 1;
   }

   // PHP 7+ code, Define
   $value = function() {
      return $this->x;
   };

   print($value->call(new A));
?>

  上述代码的输出如下:

1