Home  >  Article  >  Backend Development  >  PHP closure class

PHP closure class

王林
王林forward
2023-08-19 11:01:17837browse

PHP closure class

Introduction

Anonymous functions (also called lambdas) return objects of class Closure. 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
}

Method

private Closure::__construct (void) — This method is only used to disable instantiation of the Closure class. Objects of this class are created by anonymous functions.

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

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

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

Closure Example

Online Demonstration

<?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();
?>

Output

The above program displays the following output

Hello Amar
Hello Amar

The above is the detailed content of PHP closure class. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete