Why you should learn closure in php?

 In General

Web Development Tips

Closure is introduced in php 5.3 version. In this post we see what is closure, how to use and how it is useful for web application.

Before going to into definition and examples. Let’s see some other related terms.

Anonymous Function: A function without name is called anonymous Function. If you are from JavaScript programming backgrounds, then you must be familiar with this. This is useful to useful to define in-line function.See the below code.


// A regular function

function temp()
{
echo “Hello anonymous function”;
}

echo temp();

// Anonymous function -A function without name

function(){
echo “Hello anonymous function”;
}

// Closure & Lambda example

$temp = function(){
echo “Hello anonymous function”;
}
echo $temp();
//output – Hello anonymous function

 

In above example, anonymous function is assigned to $temp variable and then this $temp is called as function.

What is Closure?

– Closure is nothing but an object representation of the anonymous function
– The above anonymous function example, we just saw, actually returns a reference to Closure object, not only a function reference.
– Closure and Lambda are same apart from it can access variables outside the scope that it was created.


//set user name
$user = “John”;

// Create a Closure
$greeting = function() use ($user) {
echo “Hello $user”;
};

$greeting();

// Returns – “Hello John”

In the above example you have seen we closure access $user inside the function.

You can also change the $user variable within the Closure, it would not affect the original variable. To update the original variable, we can append an ampersand. An ampersand before a variable means this is a reference and so the original variable are also updated.


$i = 0;

$closure = function () use (&$i)
{
$i++;
};

$closure();
// The global count has increased
echo $i; // Returns 1

Closures are also useful when using PHP functions that accept a callback function like array_map, array_filter, array_reduce or array_walk.

The array_walk function takes an array and runs it through the callback function.


$users = array(“jay”, “amol”, “santosh”, “girish”);
// Pass the array to array_walk
array_walk($users, function ($name) {
echo “Hello $name<br>”;
});
// Returns
// -> Hello jay
// -> Hello amol
// -> ..

PHP Web Development is one of the highly sought after skills from the CodePlateau Portfolio.  CodePlateau has a tonne of experience with website development using PHP and it would serve you well to pay heed to what they have to say.

 

Resource:
PHP Manual, Anonymous Functions
PHP Manual, The Closure Class
PHP Wiki/RFC, RFC: Closures Object Extension

Recent Posts