简体   繁体   中英

Php 5.4 closures

$that = $this;
$closure = function (...) use ($that) { ... };

Found on: http://css.dzone.com/polls/what-new-feature-php-54

Could someone please explain what it does? Preferably with an example.

that is a way to have access to the methods of a class from a anonymous function defined in it. but since the title is "php 5.4 closures" you don't need to do that any more, this is one of the updates made in 5.4, you can use $this (without passing it to another variable like $that). you can see here http://php.net/ChangeLog-5.php that one of the changes is "Added closure $this support back"

A closure is an anonymous function, often used with callbacks. For example:

my_function_with_callback('some-parameter', function() {
    //Do stuff here
});

The rebinding means that you can use $this in an anomymous function, instead of having to use: 'use($var)', so when you're in a class:

class MyClass {
    public function myMethod() {
        $anon = function() {
            //$this still refers to MyClass here
        };
    }
}

Hope this answers your question

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM