Closure, anonymous function, also known as Anonymous functions, was introduced in php5.3.Anonymous functions are functions that do not have names defined. Remember this to understand the definition of anonymous functions.
Introduction to Closure class (PHP 5 >= 5.3.0) Class used to represent anonymous functions. Anonymous functions (introduced in PHP 5.3) will 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, 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 — a constructor used to prohibit instantiation
Closure::bind — Copy a closure that binds the specified $this object and class scope.
Closure::bindTo — Copy the current closure object and bind the specified $this object and 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 turn the 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 the Closure class in PHP that the editor has shared with you. I hope you like it.