PHP closure class

王林
Release: 2023-08-19 11:02:01
forward
820 people have browsed it

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
}
Copy after login

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

Output

The above program displays the following output

Hello Amar
Hello Amar
Copy after login

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

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!