Home > Article > Backend Development > When to use closures in php
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
Used in the callback function
Assign a value to an ordinary variable
Use use to inherit from the parent domain
Pass parameters
Usage in OO
_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
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!