RSpedia
Digital Marketing

What Is A Closure in PHP and how to effectively use it?

Closure in PHP

A closure is an anonymous function that closes over the environment in which it was defined.

Source

In simpler terms, it is a function that can be created without a specified name.

Closures have been introduced in PHP 5.3 and their most important use is for callback functions. 

There are many things a PHP developer can do with the closure function. To get the most out of it, hire PHP programmers. 

Let’s take an example of what a closure function looks like:

Source

This is a normal function code. To convert this into an anonymous or closure function, you will have to do this:

<?php

function () {

   echo ‘anonymous function’;

}

Now, inspect this anonymous function and arrow function. 

<?php

 //Anonymous function

 $anonymous = function () {

  return ‘lambda’;

 };

 echo get_class($anony); # Prints: Closure

 echo gettype($anony);   # Prints: object

 //Arrow function

 $arrow = fn() => ‘im an arrow func’;

 echo get_class($arrow); # Prints: Closure

 echo gettype($arrow);   # Prints: object

These are actually instances of the closure class.

Now, we will navigate how to effectively use this function and its different methods.

How to call the closure function?

You can call this function with the help of the parenthesis.

(function () {

   echo ‘anonymous function’;

})();

You can alternatively call this function by:

<?php

$bl_fn = function () {

   echo ‘anonymous function’;

};

$bl_fn()’

You just need to execute this function to get the result. 

Note – Since the function is an inline function, you need to use the semicolon. 

How to access external variables?

You already know that you can’t access the outside scope variable in the

closure. 

Here’s an example:

<?php

$ex_variable=‘Daily’:

$second_ex_variable =”Tuition”;

$myFunction = function() {

  echo $ex_variable, $second_ex_variable

};

You have two variables and both are echoes. If you try to execute this function it will return an error message saying that the variables aren’t defined.

So, you have to introduce the use function.

$ex_variable=‘Daily’:

$second_ex_variable =”Tuition”;

$myFunction = function() use ($ex_variable, $second_ex_variable) {

  echo $ex_variable, $second_ex_variable;

Through these methods you can access the external variable. 

How to use closure as a callback function?

In many of the PHP predefined functions, closures are used as callback functions.

The array map function is the first parameter of a callback function. 

Take a look at this code:

<?php

array_map(function($value){

   echo $value;

}. $arr);

Now, let’s break it down.

This is a closure function and has no name:

<?php

array_map(function($value){

});

After creating this, you have to specify the function code in {} which would be:

{

   echo $value;

}

After this, you can specify the second argument in the array map function, like $arr.

This array map function uses the closure as the argument of the function. Using the callback function you can manipulate your array value very easily. 

How to use different methods in Closure class?

Since PHP 5.4, you can use several methods that allow further control of the anonymous function after it has been created.

Source

As seen in the image, there are five methods that we are going to cover. There is also a sixth method that is not in the image – invoke. 

If you hire PHP programmers, they should know how to use these methods effectively. 

  1. bindTo() method

The Closure is essentially duplicated by the bind() and bindTo() methods, but with a specific bound object and class scope. 

The usage of closures allows you to capture context from outside the function’s scope (using use keyword). This context can include variables as well as the scope of an object. This produces a closure object with access to the object’s properties. 

Two parameter do the bindTo method: 

  • The bound object of the closure 
  • The associated class scope

The class name must be supplied as the second argument in order to access private and protected. Here’s an example:

<?php

 class A {

  private $heyearth = ‘Hello world’;

 }

 $closure = function () {

             return $this->hey earth;

            };

 $getHeyearth = $closure->bindTo(new A , ‘A’);

 echo $getHeyearth(); // Hello world

  1. bind() method

The bind() method has three parameters:

  • The anonymous functions to bind
  • The bound object of the closure 
  • The associated class scope

Here’s an example:

<?php

 class A {

  private $heyearth = ‘Hello world’;

 }

 $closure = function () {

             return $this->hey earth;

            };

 $getHeyearth = Closure: :bind($closure,new A , ‘A’);

 echo $getHeyearth(); // Hello world

  1. Call() method

The call function on a Closure class debuted in PHP 7.

 The call method temporarily binds the closure to the object and calls it with any supplied parameters rather than duplicating the closure. The closure’s return value is then returned:

<?php

 class A {

  private $heyearth = ‘Hello world’;

 }

 $closure = function () {

             return $this->hey earth;

            };

 $getHeyearth = $closure->call(new ‘);

 echo $getHeyearth; // Hello world

You can replace the anonymous function with the arrow function:

<?php

 class A {

  private $heyearth = ‘Hello world’;

 }

 $closure = fn() => $this->

             return $this->hey earth;

 $getHeyearth = $closure->call(newA);

 echo $getHeyearth; // Hello world

  1. Callable method

It converts a callable into a closure.

Code line:

Closure::fromCallable(callable $callback): Closure

Use the current scope to create and return a new anonymous function. This method checks if the callback is callable in the current scope and throws a TypeError if it is not.

It will return the newly created Closure or throw a TypeError if the callback is not callable in the current scope.

Here is a detailed example:

class A {

    private $name;

    public function __construct($name)

    {

        $this->name = $name;

    }

}

// test callable

function getName()

{

      return $this->name;

}

$bob = new A(“Bob”);

$cl1 = Closure::fromCallable(“getName”);

$cl1 = $cl1->bindTo($bob, ‘A’);

//This will retrieve: Uncaught Error: Cannot access private property A::$name 

$result = $cl1();

echo $result;

//But for a Lambda function

$cl2 = function() {

    return $this->name;

};

$cl2 = $cl2->bindTo($bob, ‘A’);

$result = $cl2();

// This will print Bob

echo $result;

  1. Construct() method

The construct method disallows instantiation.

Code:

Closure::__construct()

This function has no parameters.

  1. Invoke method

Apart from these five functions, there is also an __invoke method. The invoke method is for consistency with other classes that implement calling magic, as this method is not used for calling the function.

The __invoke() method is called when a script tries to call an object as a function.

Example:

Source

This will be the output: int(5)

bool(true)

How to use closures in itself via reference?

Look at this example to delete a directory with all subdirectories and files:

<?php

$deleteDirectory = null;

$deleteDirectory = function($path) use (&$deleteDirectory) {

    $resource = opendir($path);

    while (($item = readdir($resource)) !== false) {

        if ($item !== “.” && $item !== “..”) {

            if (is_dir($path . “/” . $item)) {

                $deleteDirectory($path . “/” . $item);

            } else {

                unlink($path . “/” . $item);

            }

        }

    }

    closedir($resource);

    rmdir($path);

};

$deleteDirectory(“path/to/directory”);

?>

In this method the closure is used in itself via reference. 

Now, you know the possibilities of the closure function in PHP. However, there are limits to how much you do effectively without the skill set. Hence, we recommend that you hire PHP programmers who are skilled and can do the task efficiently for you at cheap rates. 

Related posts

Best Site to Buy Instagram Followers UK

kajalparmar

The Need for Intelligent Marketing: What AI Can Do for Your Marketing

rspedia

5 Reasons To Go For SEO Services In India

kajalparmar

Leave a Comment