Home > Article > Backend Development > How to use the Closure class in PHP and detailed explanation, phpclosure_PHP tutorial
Closure, anonymous functions, also known as Anonymous functions, were introduced in php5.3. Anonymous function is a function without a defined name. Keep this in mind and you will be able 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) will generate objects of this type. Let’s take a look at the PHP Closure class How to use and introduction.
The PHP Closure class was introduced before 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, and 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 used to disable instantiation
Closure::bind — Copies a closure, binding the specified $this object to the class scope.
Closure::bindTo — Copies the current closure object, binding the specified $this object and class scope.
Look at 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 turn a class into a closure:
class Invoker { public function __invoke() {return __METHOD__;} } $obj = new Invoker; echo $obj(); //Invoker::__invoke
The above content is the usage method and detailed explanation of Closure class in PHP shared by the editor. I hope you like it.