Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Creating Closure function in php

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 112
    Comment on it

    In this tutorial we will learn about the closure function in php. Here we will see simple closure using an anonymous function.


    Example 1:

    // Create a user
    
    $user = "xyz";
    
    // Create a Closure
    
    $invoke = function() use($user) {
      echo "Hello $user";
    };
    
    // Greet the user
    $invoke(); // Returns "Hello xyz"
    

    Example 2:

    // A simple example of a closure
    
    function invoke() {
    
      $message = "Hello";
    
      return ( function( $name ) use ( $message ) {
        return ( "$message, $name!" );
      } );
    };
    
    $invoke = invoke();
    echo $invoke( "abcd" ); // Displays "Hello, abcd!"
    

    As we can see in the above examples, the Closure is able to access the $user/$message variable because it was declared in the use clause of the Closure function definition.

    If we alter the $user/$message variable within the Closure, it will not effect the original variable. If we want to update the original variable, we need to prepend an ampersand (& ) to the $user/$message variable as a reference which will updated the original value of $user/$message.

    Example3:

    // Create a user
    
    $user = "xyz";
    
    // Create a Closure
    
    $invoke = function() use(&$user) {
      echo "Hello $user";
    };
    
    $user = "abcd";
    // Invoke the user
    $invoke(); // Returns "Hello abcd"
    

    Link to create anonymous function

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: