Skip to content

PHP Closures and Anonymous functions

Last updated on June 23, 2015

Anonymous functions are also known as Lambda functions. Lambda function and closures are the functions with no name. Anonymous functions has same variable scope characteristics as closures.And all anonymous functions are closures but all closures are not anonymous functions.

In PHP there is no much difference between lambdas and closures, the only differences is, anonymous function created using the use() keyword is a closure.

Lambda functions are just throw-away functions (inline functions), that are not used elsewhere in the application, they are merely callback functions.

You can assign these functions to a variable, so you can pass it around. Closures bind references to non-local variables to local variables inside the function at the time of the Closure definition. Variables defined inside the closure are not accessible from outside the closure either.

Anonymous / Lambda function:

// Anonymous function
$message = function () {
  return "Hello world";
}

Echo $message();

Closure Function:

$message = function () use ($text)  {
return $text;
}
echo $message(“Hello World”);

Closure Variable Scope:

 function incrementClosure() {
        $local_var = 1;
        return function() use (&$local_var) {
            return ++$local_var;
            };
    }
$incrementClosure = incrementClosure();
$incrementClosure(); // output : 2
$incrementClosure(): // output :3
$incrementClosureNew = incrementClosure();
$incrementClosureNew(); // output : 2
$incrementClosure(): // output :4
$incrementClosureNew(): // output :3

Closure Function instead of callback implementation:

$numbersIncrement = array_map(function ($number) {    
return $number + 1; }, [1,2,3]); 
print_r($numbersIncrement); 
// Outputs --> [2,3,4]

Multiple arguments to Closure

$message = function () use ($greeting,$firstName,$lastName)  {
return $greeting.' '.$firstName.' '.$lastName;
}
echo $message(“Welcome”,"Arjun","PHP");

PHP closures are objects, right. So closure instance has its own internal state that is accessible with the $this keyword just like any other PHP object. A closure object’s has a magic __invoke() method and a bindTo() method. That’s it. The bindTo() method lets us bind a Closure object’s internal state to a different object. The bindTo() method accepts an important second argument that specifies the PHP class of the object to which the closure is bound. This lets the closure access protected and private member variables of the object to which it is bound.

public function addToEmailNotificationList($name, $emailStatusCallback) {         
  $this->names[$name] = $emailStatusCallback->bindTo($this, __CLASS__); 
} 

That is it.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments