The usage scenarios of closures in PHP are: 1. When calling static classes dynamically; 2. Used in callback functions; 3. Assigned to an ordinary variable; 4. Use use to inherit from the parent domain. ;5. When passing parameters, etc.
The usage scenarios of closures in php are: when dynamically calling a static class, use it in the callback function, assign it to an ordinary variable, use use When inheriting from the parent domain and passing parameters
Closure function
Anonymous function, also called closure function (closure), allows temporary Creates a function without a specified name. The value most commonly used as a callback function argument. Of course, there are other applications as well.
Usage scenarios
When dynamically calling a static class
<?php class test { public static function getinfo() { var_dump(func_get_args()); } } call_user_func(array('test', 'getinfo'), 'hello world');
Used in the callback function
<?php //eg array_walk array_map preg_replace_callback etc echo preg_replace_callback('~-([a-z])~', function ($match) { return strtoupper($match[1]); }, 'hello-world'); // 输出 helloWorld ?>
Assign a value to an ordinary variable
<?php $greet = function($name) { printf("Hello %s\r\n", $name); }; $greet('World'); $greet('PHP'); ?>
Use use to inherit from the parent domain
<?php $message = 'hello'; // 继承 $message $example = function () use ($message) { var_dump($message); }; echo $example(); // Inherit by-reference $example = function () use (&$message) { var_dump($message); }; echo $example(); // The changed value in the parent scope // is reflected inside the function call $message = 'world'; echo $example();
Pass parameters
<?php $example = function ($arg) use ($message) { var_dump($arg . ' ' . $message); }; $example("hello");
Usage in OO
<?php class factory{ private $_factory; public function set($id,$value){ $this->_factory[$id] = $value; } public function get($id){ $value = $this->_factory[$id]; return $value(); } } class User{ private $_username; function __construct($username="") { $this->_username = $username; } function getUserName(){ return $this->_username; } } $factory = new factory(); $factory->set("zhangsan",function(){ return new User('张三'); }); $factory->set("lisi",function(){ return new User("李四"); }); echo $factory->get("zhangsan")->getUserName(); echo $factory->get("lisi")->getUserName();
Call in function
<?php function call($callback){ $callback(); } call(function() { var_dump('hell world'); });
The above is the detailed content of When to use closures in php. For more information, please follow other related articles on the PHP Chinese website!