search
HomeBackend DevelopmentPHP TutorialIntroduction to how to use Closure to create anonymous functions in PHP

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.

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

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

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

The output of the above function is similar to bind

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

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

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

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!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
Explain the concept of session locking.Explain the concept of session locking.Apr 29, 2025 am 12:39 AM

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Are there any alternatives to PHP sessions?Are there any alternatives to PHP sessions?Apr 29, 2025 am 12:36 AM

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

What is the full form of PHP?What is the full form of PHP?Apr 28, 2025 pm 04:58 PM

The article discusses PHP, detailing its full form, main uses in web development, comparison with Python and Java, and its ease of learning for beginners.

How does PHP handle form data?How does PHP handle form data?Apr 28, 2025 pm 04:57 PM

PHP handles form data using $\_POST and $\_GET superglobals, with security ensured through validation, sanitization, and secure database interactions.

What is the difference between PHP and ASP.NET?What is the difference between PHP and ASP.NET?Apr 28, 2025 pm 04:56 PM

The article compares PHP and ASP.NET, focusing on their suitability for large-scale web applications, performance differences, and security features. Both are viable for large projects, but PHP is open-source and platform-independent, while ASP.NET,

Is PHP a case-sensitive language?Is PHP a case-sensitive language?Apr 28, 2025 pm 04:55 PM

PHP's case sensitivity varies: functions are insensitive, while variables and classes are sensitive. Best practices include consistent naming and using case-insensitive functions for comparisons.

How do you redirect a page in PHP?How do you redirect a page in PHP?Apr 28, 2025 pm 04:54 PM

The article discusses various methods for page redirection in PHP, focusing on the header() function and addressing common issues like "headers already sent" errors.

Explain type hinting in PHPExplain type hinting in PHPApr 28, 2025 pm 04:52 PM

Article discusses type hinting in PHP, a feature for specifying expected data types in functions. Main issue is improving code quality and readability through type enforcement.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.