Home  >  Article  >  Backend Development  >  The role of php closures

The role of php closures

WBOY
WBOYOriginal
2016-12-01 00:57:111026browse

<code>    public function __construct($config)
    {
    parent::__construct();
    $this['config'] = function () use ($config) {
        return new Config($config);
    };
    ...
    其中
    $this['config'] = function () use ($config) {
        return new Config($config);
    能不能直接写成这样:
    $this['config'] = new Config($config);
    有什么优势?</code>

Reply content:

<code>    public function __construct($config)
    {
    parent::__construct();
    $this['config'] = function () use ($config) {
        return new Config($config);
    };
    ...
    其中
    $this['config'] = function () use ($config) {
        return new Config($config);
    能不能直接写成这样:
    $this['config'] = new Config($config);
    有什么优势?</code>

Lazy loading. Both ways of writing are fine, however.
$this['config'] = new Config($config);
In this way, when you assign a value to $this->['config'], new Config($ config)operation.

<code class="php">$this['config'] = function () use ($config) {
        return new Config($config);
}</code>

In this way, you just give $this->['config'] an anonymous function, and when you want to use it, you will perform the new Config($config) operation.

I don’t know if my explanation is correct= =It’s not very expressive= =

<code>能不能直接写成这样:
$this['config'] = new Config($config);
有什么优势?</code>

It can be written like this, but it will go to the new Config class every time it is instantiated, and it does not matter whether it is used or not;

<code>$this['config'] = function () use ($config) {
        return new Config($config);
}</code>

This way of writing is to declare an anonymous function for $this['config']. When $this['config'] is actually called, the new Config class will be accessed;

The advantage of writing like this is that when $this['config'] is not actually used, it reduces the additional instantiation process and memory consumption

closure will create a new Config when it is actually called, so that lazy load can be achieved.

In addition to the above lazy loading, another advantage is that it implements a factory mode -- every time you get the config, it will be new

1. Lazy loadingEveryone has mentioned it

2. In fact, anonymous functions are largely a manifestation of functional programming

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