Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Using closure function for passing data to callbacks

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 86
    Comment on it

    Here we will see example of how we can pass data using closure function.As we've seen how to create a closure, let's see how we can use them.

    When we pass a callback function to the PHP usort() function, and usort() calls our callback, the callback receives the two arguments passed to it by usort() that is, the two values in the array to compare.

    How to let the callback function receive more information?

    Let us take an example of usort().Here we will pass additional $key arguments to our callback function to tell it what key it should use ("name" or "age").

    $person = array(
      array( "NAME" => "A", "AGE" => 25 ),
      array( "NAME" => "X", "AGE" => 19 ),
      array( "NAME" => "L", "AGE" => 52 )
    );
    
    function invoke( $key ) {
    
     //Defined anonymous function also use keyword is used to make a closure.
      return function( $personA, $personB ) use ( $key ) {
        return ( $personA[$key] < $personB[$key] ) ? -1 : 1;
      };
    }
    
    echo "SORTING BY NAME:<br>";
    
    usort( $person, invoke( "NAME" ) );
    echo '<pre>';print&#95;r($person);
    echo "<br>";
    
    echo "SORTING BY NAME:<br>";
    usort($person, invoke("AGE") );
    echo '<pre>';print&#95;r($person); 
    
    OUTPUT:
    
    SORTING BY NAME:
    
    Array
    (
        [0] => Array
            (
                [NAME] => A
                [AGE] => 25
            )
    
        [1] => Array
            (
                [NAME] => L
                [AGE] => 52
            )
    
        [2] => Array
            (
                [NAME] => X
                [AGE] => 19
            )
    
    )
    
    SORTING BY AGE:
    
    Array
    (
        [0] => Array
            (
                [NAME] => X
                [AGE] => 19
            )
    
        [1] => Array
            (
                [NAME] => A
                [AGE] => 25
            )
    
        [2] => Array
            (
                [NAME] => L
                [AGE] => 52
            )
    
    )
    

 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: