PHP started supporting closure from 5.3.0 version, but still many PHP programmers don’t know/make effective use of it yet. I also haven’t seen that much articles on it as well. In today’s PHP closure tutorial, I will try to cover how you can start using it easily and make your web application more robust/optimized. Before drive into real examples, assuming that, you are pretty new with this term, lets know few related definitions first:
Anonymous Function: Anonymous function is what its title implies, a function without a name. If you have worked with JavaScript, you should have already familiar with such functions. These pretty useful to write short inline functions, define callback etc. A code example of a PHP anonymous function:
1
2
3
4
5
6
$functionReference = function(){
echo "anonymous function called";
};
echo $functionReference();
//prints: "anonymous function called"
You can read more details about php anonymous function on official documentation.
Lazy Loading: Lazy loading is a common design pattern, which indicates about deferring loading of an object until it is really required. Why I used this term on this article? Our closure/anonymous function actually will help us achieve this feature, that’s why. You will get more clear picture, just read on.
What is Closure:
Well, closure is nothing but an object representation of anonymous function. It is the object-oriented way to use anonymous function. More interestingly, the above anonymous function example we just saw, actually returns a reference of Closure object, not only a function reference. Thus, the PHP closure method ‘bindTo‘ can be applied on this reference. The other ‘bind‘ method is static and alternate way to get the same behavior.
Pretty simple staff! Right? I am not giving any example here as you will see them already on different use cases.
What We Can Do With Closure?
Here, I will describe two simple yet powerful features that PHP closure offers us to use:
accessing private data of an object instance and
lazy loading
Access Private variable using closure:
A simple example below will show you one of the super power of closure, accessing private variable of an object:
01
02
03
04
05
06
07
08
09
10
11
class SimpleClass {
private $privateData = 2;
}
$simpleClosure = function() {
return $this->privateData;
};
$resultClosure = Closure::bind($simpleClosure, new SimpleClass(), 'SimpleClass');
echo $resultClosure();
See? So, if we just know the variable name, it’s a awesome way to use private data without modifying existing class. Same way we can add/inject new behavior to a php class without modifying it as well.
Lazy Loading With PHP Closure:
As we have seen the definition, lazy loading will help preventing any initialization until it is used. Lets see an example how we can achieve this. We will define a monolog debug logger, which will only be used in some certain specific cases.
01
02
03
04
05
06
07
08
09
10
11
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
$logClosure = function() {
$log = new Logger('event');
$log->pushHandler(new StreamHandler("logfile.log", Logger:
EBUG));
return $log;
};
//logger will not be initialized until this point
$logger = $logClosure();
So, as you can see here, we can write all definitions, without actual initialization happen using closure. Later when needed, use it with simple assignment as ‘$logger = $logClosure()’.
Using External Variable inside closure:
As closure body only be executed on demand, passing some external value/variable is a little different. You will just have to use a new ‘using’ keyword for this on php closure function definition. Lets see another example:
1
2
3
4
5
$someValue = "sample external data";
$simpleClosure = function() use($someValue) {
return "Test accessing external value inside closure ".$someValue;
};
echo $simpleClosure();
What’s Next?
PHP Closure implementation is being frequently used in modern applications/frameworks. So, why not you? Give it a try. Happy Coding!
Anonymous Function: Anonymous function is what its title implies, a function without a name. If you have worked with JavaScript, you should have already familiar with such functions. These pretty useful to write short inline functions, define callback etc. A code example of a PHP anonymous function:
1
2
3
4
5
6
$functionReference = function(){
echo "anonymous function called";
};
echo $functionReference();
//prints: "anonymous function called"
You can read more details about php anonymous function on official documentation.
Lazy Loading: Lazy loading is a common design pattern, which indicates about deferring loading of an object until it is really required. Why I used this term on this article? Our closure/anonymous function actually will help us achieve this feature, that’s why. You will get more clear picture, just read on.
What is Closure:
Well, closure is nothing but an object representation of anonymous function. It is the object-oriented way to use anonymous function. More interestingly, the above anonymous function example we just saw, actually returns a reference of Closure object, not only a function reference. Thus, the PHP closure method ‘bindTo‘ can be applied on this reference. The other ‘bind‘ method is static and alternate way to get the same behavior.
Pretty simple staff! Right? I am not giving any example here as you will see them already on different use cases.
What We Can Do With Closure?
Here, I will describe two simple yet powerful features that PHP closure offers us to use:
accessing private data of an object instance and
lazy loading
Access Private variable using closure:
A simple example below will show you one of the super power of closure, accessing private variable of an object:
01
02
03
04
05
06
07
08
09
10
11
class SimpleClass {
private $privateData = 2;
}
$simpleClosure = function() {
return $this->privateData;
};
$resultClosure = Closure::bind($simpleClosure, new SimpleClass(), 'SimpleClass');
echo $resultClosure();
See? So, if we just know the variable name, it’s a awesome way to use private data without modifying existing class. Same way we can add/inject new behavior to a php class without modifying it as well.
Lazy Loading With PHP Closure:
As we have seen the definition, lazy loading will help preventing any initialization until it is used. Lets see an example how we can achieve this. We will define a monolog debug logger, which will only be used in some certain specific cases.
01
02
03
04
05
06
07
08
09
10
11
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
$logClosure = function() {
$log = new Logger('event');
$log->pushHandler(new StreamHandler("logfile.log", Logger:

return $log;
};
//logger will not be initialized until this point
$logger = $logClosure();
So, as you can see here, we can write all definitions, without actual initialization happen using closure. Later when needed, use it with simple assignment as ‘$logger = $logClosure()’.
Using External Variable inside closure:
As closure body only be executed on demand, passing some external value/variable is a little different. You will just have to use a new ‘using’ keyword for this on php closure function definition. Lets see another example:
1
2
3
4
5
$someValue = "sample external data";
$simpleClosure = function() use($someValue) {
return "Test accessing external value inside closure ".$someValue;
};
echo $simpleClosure();
What’s Next?
PHP Closure implementation is being frequently used in modern applications/frameworks. So, why not you? Give it a try. Happy Coding!