Home > Backend Development > PHP Tutorial > Introduction to how to use Closure to create anonymous functions in PHP

Introduction to how to use Closure to create anonymous functions in PHP

青灯夜游
Release: 2023-04-09 11:48:01
forward
1869 people have browsed it

Introduction to how to use Closure to create anonymous functions in PHP

Closure class

A class used to represent anonymous functions.

Anonymous functions (introduced in PHP 5.3) produce objects of this type. In the past, this class was considered an implementation detail, but now it can be relied upon to do something. As of PHP 5.4, this class comes with methods that allow more control over the anonymous function after it has been created.

This class cannot be instantiated. There are two main methods in it, both of which are used to copy closures, one static and one dynamic. These two difficult-to-understand methods are explained in detail below.

Closure::bind

public static Closure Closure::bind ( Closure $closure , object $newthis [, mixed $newscope = 'static' ] )

参数说明:
closure
需要绑定的匿名函数。

newthis
需要绑定到匿名函数的对象,或者 NULL 创建未绑定的闭包。

newscope
想要绑定给闭包的类作用域,或者 'static' 表示不改变。如果传入一个对象,则使用这个对象的类型名。 类作用域用来决定在闭包中 $this 对象的 
私有、保护方法 的可见性。 The class scope to which associate the closure is to be associated, or 'static' to keep the 
current one. If an object is given, the type of the object will be used instead. This determines the visibility of 
protected and private methods of the bound object.
Copy after login

Parameter description:

  • closure needs to be bound anonymously function.

  • newthis requires an object bound to an anonymous function, or NULL to create an unbound closure.

  • newscope wants to be bound to the class scope of the closure, or 'static' means no change. If an object is passed in, the type name of the object is used. Class scope is used to determine the visibility of private, protected methods of the $this object within the closure.

The class scope to which associate the closure is to be associated, or 'static' to keep the

current one. If an object is given, the type of the object will be used instead. This determines the visibility of

protected and private methods of the bound object.

The above is the definition of the method,

The first parameter is easy to understand, it is a closure function;

The second parameter is not easy to understand. If the closure to be copied contains $this, this The object represents this $this. Modifications to this object in the closure function will remain consistent after the call is completed, such as modifying an attribute;

The third parameter is not so It’s easy to understand, but the official instructions are confusing. With the default parameters, when calling $this-> to access the attribute function in object $newthis, it will There are restrictions. You can only access functions with public attributes. If you want to access protected/private attributes, you must set them to the corresponding class name/class instance, just like in the class. , to access the protected/private attribute functions of that class.

Example

<?php
class T {
    private function show()
    {
        echo "我是T里面的私有函数:show\n";
    }

    protected  function who()
    {
        echo "我是T里面的保护函数:who\n";
    }

    public function name()
    {
        echo "我是T里面的公共函数:name\n";
    }
}

$test = new T();

$func = Closure::bind(function(){
    $this->who();
    $this->name();
    $this->show();
}, $test);

$func();
Copy after login

The above code will report an errorFatal error: Uncaught Error: Call to protected method T::who() from context 'Closure'. Add the third parameter of bind to t::class or new T(), and each result will be output normally.

我是T里面的保护函数:who
我是T里面的公共函数:name
我是T里面的私有函数:show
Copy after login

Of course, closures can also pass parameters

$test = new StdClass();
var_dump($test);

$func = Closure::bind(function($obj){
    $obj->name = "燕睿涛";
}, null);

$func($test);
var_dump($test);
Copy after login

The above program is the same as the anonymous function and has no dependencies on any objects. The above program will output:

object(stdClass)#1 (0) {
}
object(stdClass)#1 (1) {
  ["name"]=>
  string(9) "燕睿涛"
}
Copy after login

There is also a special example that needs to be explained

<?php
class T {
    private function show()
    {
        echo "我是T里面的私有函数:show\n";
    }

    protected  function who()
    {
        echo "我是T里面的保护函数:who\n";
    }

    public function name()
    {
        echo "我是T里面的公共函数:name\n";
    }
}

$func = Closure::bind(function ($obj) {
    $obj->show();
}, null);

$test = new T();

$func($test);
Copy after login

What will be output in the above situation? Yes, an error will be reported, indicating that the private attribute cannot be accessedshow. At this time, add the third Just one parameter is enough. After seeing that the third parameter not only affects the scope of $this,
can also affect the scope of the parameter.

Closure::bindTo

bindTo has similar functions to bind, here is just another one Both forms copy the current closure object and bind the specified $this object and class scope. , the first parameter is less than bind,
the last two are the same, of course there is another difference that bindTo is not a static method, it exists only because of a closure a property method.

Example

<?php
class T {
    private function show()
    {
        echo "我是T里面的私有函数:show\n";
    }

    protected  function who()
    {
        echo "我是T里面的保护函数:who\n";
    }

    public function name()
    {
        echo "我是T里面的公共函数:name\n";
    }
}

$func = function () {
    $this->show();
    $this->who();
    $this->name();
};

$funcNew = $func->bindTo(new T(), T::class);

$funcNew();
Copy after login

The output of the above function is similar to bind

我是T里面的私有函数:show
我是T里面的保护函数:who
我是T里面的公共函数:name
Copy after login

a trick

This function was encountered when looking at the automatic loading source code generated by composer. It is used in a special way in composer. The following is an interception of part of the code in composer

// 文件autoload_real.php
call_user_func(\Composer\Autoload\ComposerStaticInit898ad46cb49e20577400c63254121bac::getInitializer($loader));

// 文件autoload_static.php
public static function getInitializer(ClassLoader $loader)
{
    return \Closure::bind(function () use ($loader) {
        $loader->prefixLengthsPsr4 = ComposerStaticInit25885cdf386fdaafc0bce14bb5a7d06e::$prefixLengthsPsr4;
        $loader->prefixDirsPsr4 = ComposerStaticInit25885cdf386fdaafc0bce14bb5a7d06e::$prefixDirsPsr4;
        $loader->prefixesPsr0 = ComposerStaticInit25885cdf386fdaafc0bce14bb5a7d06e::$prefixesPsr0;
        $loader->classMap = ComposerStaticInit25885cdf386fdaafc0bce14bb5a7d06e::$classMap;

    }, null, ClassLoader::class);
}
Copy after login

The above code is rather strange. In call_user_func, the first impression is that the wrong parameters are passed. In fact, this is not the case. A function is called here, and this function will return a Closure object,
It is an anonymous function, and the final parameter passed in is still a callable type. Look at the returned closure again. use is used in it. This is the bridge connecting the closure and external variables.
As for why ordinary parameters can be passed here, it is because in php5, the object formal parameters and actual parameters point to the same object, and modifications to the object in the function will be reflected outside the object.

So, it’s okay to do the above, there is another form too

call_user_func(\Composer\Autoload\ComposerStaticInit898ad46cb49e20577400c63254121bac::getInitializer(), $loader);

public static function getInitializer()
{
    return \Closure::bind(function ($loader) {
        $loader->prefixLengthsPsr4 = ComposerStaticInit25885cdf386fdaafc0bce14bb5a7d06e::$prefixLengthsPsr4;
        $loader->prefixDirsPsr4 = ComposerStaticInit25885cdf386fdaafc0bce14bb5a7d06e::$prefixDirsPsr4;
        $loader->prefixesPsr0 = ComposerStaticInit25885cdf386fdaafc0bce14bb5a7d06e::$prefixesPsr0;
        $loader->classMap = ComposerStaticInit25885cdf386fdaafc0bce14bb5a7d06e::$classMap;

    }, null, ClassLoader::class);
}
Copy after login

Summary

I haven’t blogged for a long time. Sometimes I’m too irritable and can’t calm down. Sometimes I just can’t find what I want to write. You still have to calm down, do everything well, don't be agitated when things happen, keep an open mind, and handle everything calmly.

Related tutorial recommendations: "PHP Tutorial"

The above is the detailed content of Introduction to how to use Closure to create anonymous functions in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
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