Closing Php 5.4

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


Found at:

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


source to share

2 answers

it is a way to access the methods of a class from an anonymous function defined in it. but since you no longer need the "closing php 5.4" title, this is one of the updates made in 5.4, you can use $ this (without passing it to another variable such as $ this). you can see here that one of the changes is: "Added closing $ this support back"



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

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


The reversal means that you can use $ this in an anonymous function, instead of using: 'use ($ var)', so when you are in a class:

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


Hope this answers your question.



All Articles