closure, anonymous function,Also called anonymous functions, was introduced in php5.3.Anonymous functions are functions with no defined name. Keep this in mind to understand the definition of anonymous functions.

Introduction to the closure class (php 5>= 5.3.0) A class used to represent anonymous functions. Anonymous functions (introduced in php 5.3) produce objects of this type,Let's take a look at the usage and introduction of the php closure class.

The php closure class was previously introduced in the php predefined interface,But it is not an interface, it is an internal final class. The closure class is used to represent anonymous functions.All anonymous functions are instances of the closure class.

$func=function () {
  echo "func called";
var_dump ($func);//class closure #1 (0) {}
$reflect=new reflectionclass ("closure");
var_dump (
  $reflect->isinterface (), //false
  $reflect->isfinal (), //true
  $reflect->isinternal () //true

The closure class structure is as follows:

closure ::__ construct — Constructor to suppress instantiation

closure ::bind — copy a closure,Binds the specified $this object to the class scope.

closure ::bindto — copy the current closure object,Binds the specified $this object to the class scope.

See an example of binding $this object and scope:

class lang
  private $name="php";
$closure=function () {
  return $this->name;
$bind_closure=closure ::bind ($closure, new lang (), "lang");
echo $bind_closure ();//php

In addition, PHP uses the magic method __invoke () to make the class a closure:

class invoker {
  public function __invoke () {return __method__;}
$obj=new invoker;
echo $obj ();//invoker ::__ invoke

The above is the usage and detailed explanation of the closure class in PHP that we share with you.Hope you like it.

  • Previous jQuery + PHP star rating implementation method
  • Next Detailed explanation of unicode transcoding method in js