Computer >> Computer tutorials >  >> Programming >> PHP

PHP Closure class


Introduction

Anonymous functions (also called lambda) return object of Closure class. This class has some additional methods that provide further control over anonymous functions.

Syntax

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
}

Methods

private Closure::__construct ( void ) — This method exists only to disallow instantiation of the Closure class. Objects of this class are created by anonymous function.

public static Closure::bind ( Closure $closure , object $newthis [, mixed $newscope = "static" ] ) − Closure — Duplicates a closure with a specific bound object and class scope. This method is a static version of Closure::bindTo().

public Closure::bindTo ( object $newthis [, mixed $newscope = "static" ] ) − Closure — Duplicates the closure with a new bound object and class scope. Creates and returns a new anonymous function with the same body and bound variables, but with a different object and a new class scope.

public Closure::call ( object $newthis [, mixed $... ] ) − mixed — Temporarily binds the closure to newthis, and calls it with any given parameters.

Closure Example

<?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")). "\n";;
// using bind method
$sayhello = $hello->bindTo(new A("Amar"),'A');
echo $sayhello();
?>

Output

Above program shows following output

Hello Amar
Hello Amar