Home > Backend Development > PHP Tutorial > The role of php closures

The role of php closures

WBOY
Release: 2023-03-02 09:30:01
Original
1039 people have browsed it

<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>
Copy after login
Copy after login

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>
Copy after login
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template