Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Anonymous function

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.43k
    Comment on it

    Hello friends,

    Today we will learn about the anonymous function in PHP. Anonymous function is a function without a name. In other words, a function that does not have a name is called anonymous function.

    While defining a normal function in PHP syntax will be as follows:

    function FunctionName() {
      //function body
    }

    FunctionName is the name of the function which is used while calling the function. But the anonymous function syntax is as follows:

    function() {
      return "anonymous function";
    };

    As you are seeing in the above syntax there is no name. You can also pass parameter to anonymous function as follows:

    function( $var1, $var2 ) {
      return ( "$var1 and $var2 are the parameter" );
    };

    Anonymous function is like an expression.That's why it is ended with semicolon(;).

    You can use anonymous function in following ways:

    • Assigned to a variable:
      You can assign the anonymous function to a variable and call the variable whenever required. For example:
      <?php $callfunc = function($var) {
          return $var;
      };
      
      print $callfunc('Assigned to a variable'); 
      ?>
    • Passed as a parameter:
      Another way is to pass the anonymous function as a parameter to another function.
      <?php $users = [
          ['name' => 'name1', 'age' => 2], 
          ['name' => 'name2', 'age' => 4], 
          ['name' => 'name3', 'age' => 8]
      ];
      
      // Map function applying anonymous function
      print_r($userName = array_map(function($user) {
          return 'Hello '.$user['name'];
      }, $users));
      ?>

       

 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: