Home  >  Article  >  Backend Development  >  When to use closures in php

When to use closures in php

清浅
清浅Original
2019-05-10 14:31:534264browse

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.

When to use closures in php

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn