Closures in PHP

Today we will learn a very interesting topic known as closure in this Closures in PHP tutorial.

    • PHP started supporting closure since version 5.3.0.
    • Before understanding closure let us first understand some terms.
    • Lazy Loading: Lazy loading terms that the loading of an object is delayed until it is really required.
    • Anonymous function: An anonymous function is a function without name. It is assigned to a variable or provided as a parameter to another function.
    • Let us see an example of anonymous function:
<?php
       $string = function(){
			return "This is an anonymous function";
		  };
	
	echo $string();
?>
//output: This is an anonymous function.
    • Here we have defined a function with no name which returns a string and this function is assigned to a variable $string. The variable is then called as a function. Note that the anonymous function is ended with a semicolon.
    • What is closure? Now we can understand the term closure very well. A closure is an object representation of an anonymous function. We can see that the anonymous function in the above code actually returns an object of closure which is assigned to and called using the variable $string. You can say closure is an object oriented way to use anonymous functions.
    • Similar to closure there are lambda functions, but closures are advanced than them.
    • Closures are small use once and throw away functions which are more useful as parameters for callback functions like array_walk, array_map, array_filter etc.
    • Uses of closure:
      • Closures can access private data of an object instance.
      • In Lazy loading.
    • As an advanced feature than lambda functions closure can access data external to it. For example. It can access data of the class/function in which it is written or if it is not written in any class or function it can access the data directly specified.
    • But using external data into closure uses a different syntax. To use external data, it has to be specified in the use clause of the closure. See the following example below:
<?php
$client="Richa";
$output=function() use($client){
		echo "Welcome ".$client;
};

$output();
?>
//output: Welcome Richa
    • Here, we have a value Richa in variable $client. It is used / accessed inside the anonymous function using use clause. The closure object is stored in $outout variable and then the function is called using this variable.
    • If you want to change the value of external variable accessed inside the closure, you can do it by passing the value by reference so that the change occurs at the actual location of the value.
    • The above example is modified for it and shown below:
<?php
$client="Richa";
$output=function() use(&$client){
		$client="Monica";
		echo "Welcome ".$client;
};
echo "Before change:<br>&nbsp;&nbsp;&nbsp;&nbsp;Welcome ".$client."<br><br>";
echo "After change:<br>&nbsp;&nbsp;&nbsp;&nbsp;";
$output();
?>
    • In this example the value in the use clause is passed by reference.
    • Output of the above example is shown below:

 

parameter_pass_by_reference
fig 1

    • Closures can also access all the private data of a class; we have seen this use of closure before. Let us see it in an example:
<?php
class worker
{
	private $id;
	private $sal;
	
	public function __construct($id,$salary)
	{
		$this->id=$id;
		$this->sal=$salary;
	}
	
	public function info(){
			return function(){
			return "ID = {$this->id} <br>Salary = {$this->sal}.";
		};
	}
	
}
$work=new worker(101,10000);
$work->info();
//output:
// ID = 101
// Salary = 10000.
    • Here we are accessing the private members $id and $sal in the closure.
    • In a closure defined inside a class if you don’t want to allow it to use the data in the class, you can prefix it with static keyword.
    • When you use static keyword, the closure is not allowed to use the data in the class.
    • This helps us to save memory needed to store the object data when used in the closure. This is more useful when you use more than one closure in a class. Just prefix that closure with static keyword which should not use the class data.
    • The example is shown below:
<?php
class Plane
{
	private $id;
	
	public function __construct($id)
	{
		$this->id=$id;
	}
	
	public function company($comp)
	{
		return static funciton() use($comp){
			echo "This is a ".$comp." plane.";
		}; 
	}
}

$plane=new Plane();
$plane->company("Indian Airlines");
?>
    • This is just an example of how to use a static keyword with closure.
    • Here we have not used any of the class data inside the closure. If we use it, it will give us an error.
    • Next interesting feature is the use of __invoke() method.
    • This method allows the object of a class itself to become a closure.
    • When we define a __invoke method in a class and then call the class object as a function, the __invoke method is automatically called and executed treating the class object as a closure.
    • Let us see an example:
<?php
class Plane
{
	public function __invoke()
	{
		echo "This is an Indian Airlines plane.";
	}
}

$plane=new Plane();
$plane();
?>
//output:
// This is an Indian Airlines plane.
  • It is a magic method which makes the class itself to act as a closure.

 

Thus we learned closure in this Closures in PHP tutorial. It is useful to use closures instead of functions when there is a small task and is to be used only once in the script.

2 COMMENTS

  1. Super complete and informative article. I really enjoyed reading it. Please add an RSS only for php articles of your website. These articles are great. Thanks.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -