首頁  >  文章  >  後端開發  >  PHP閉包類

PHP閉包類

王林
王林轉載
2023-08-19 11:01:17797瀏覽

PHP閉包類

介紹

匿名函數(也稱為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 [, mixed $newscope = "static" ] ) − Closure — 使用特定綁定物件和類別作用域複製閉包。此方法是Closure::bindTo()的靜態版本。

public Closure::bindTo ( object $newthis [, mixed $newscope = "static" ] ) − Closure — 使用新的綁定物件和類別作用域複製閉包。建立並傳回一個具有相同主體和綁定變量,但具有不同物件和新類別作用域的新匿名函數。

public Closure::call ( object $newthis [, mixed $... ] ) − mixed — 將閉包暫時綁定到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"),&#39;A&#39;);
echo $sayhello();
?>

輸出

#上述程式顯示下列輸出

Hello Amar
Hello Amar
#

以上是PHP閉包類的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除