Home  >  Article  >  Backend Development  >  php Closure creates anonymous function

php Closure creates anonymous function

怪我咯
怪我咯Original
2017-06-28 11:22:451165browse

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.

The above is the definition of this method. The first parameter is easy to understand, it is a closure function; the second parameter is not It’s easy to understand. If the closure to be copied contains $this, this object represents this
$this. The modification of this object in the closure function ends at the end of the call. It will remain consistent in the future, for example, if an attribute is modified; the third parameter is not easy to understand, and the official instructions are also unclear.
With default parameters, call $this-&gt ;When accessing the attribute functions in object $newthis, there will be restrictions. You can only access the functions with public attributes. If you want to access protected/privateAttribute,
must be set to the corresponding class name/class instance, and the protected/private attribute function of that class must be accessed just like in the 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();

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<a href="http://www.php.cn/wiki/167.html" target="_blank">::class</a> or new T(), and each result will be output normally.

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

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);

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) "燕睿涛"
}

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);

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 form, both areCopy 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();

The output of the above function is similar to bind

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

A trick

This function is generated by watching composer The is encountered when loading the source code automatically. It is used in composer in a special way. 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);
}

The above code is rather strange, in call_user_func In , the first impression is that the wrong parameters are passed. In fact, this is not the case. A function is called here. This function will return a Closure object.
is also an anonymous function. The final passed in The parameter 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 the modification of the object in the function will be reflected outside the object.

So, it’s okay to do the above, there is another way 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);
}

The above is the detailed content of php Closure creates anonymous function. 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