Send function as parameter php

PHP: Assign a function to a variable.

This is a short guide on how to assign an anonymous function to a variable in PHP and then call it. Note that these kind of functions are sometimes referred to as lambda functions.

Let’s start off with a simple example with no parameters:

//Create an anonymous function and assign it to a PHP variable. $myAnonymousFunction = function()< echo "Hello World!"; >; //Call our anonymous function. $myAnonymousFunction();

In the code above, we created a very basic anonymous PHP function and assigned it to a variable called $myAnonymousFunction. As a result, we were then able to call the function in question by referencing $myAnonymousFunction.

Anonymous function with parameters.

Now, let’s create an anonymous PHP function that takes in parameters:

//This anonymous function takes in a parameter //called $name. $sayHello = function($name)< echo "Hello $name!"; >; //Call our anonymous function and pass in //the parameter. $sayHello('Wayne');

As you can see, this example doesn’t differ too much from our first one. The only difference is that it takes in a parameter called $name and prints it out.

Passing one anonymous function into another.

You can also pass one anonymous function in as a parameter to another anonymous function:

//Create our first anonymous function. $functionOne = function()< echo 'Hi everybody'; >; //Create our second anonymous function. $functionTwo = function($function)< $function(); >; //Pass one anonymous function into another. $functionTwo($functionOne);

In the code above, we created two functions and assigned them to PHP variables. The first function prints out a string, whereas the second one takes in a function as a parameter before calling it. Furthermore, we passed the first function into the second function.

Читайте также:  Переменная булеан в питоне

As a result, the script above will print the words “Hi everybody” to the browser.

Oh, and by the way, I am not sorry for putting Dr. Nick’s voice in your head.

Источник

Lambda Functions in PHP

Lambda Functions in PHP

  1. Demonstrate How to Pass a Lambda Function as a Parameter in PHP
  2. Demonstrate How to Store a Lambda Function in a Variable in PHP
  3. Difference Between Lambda and Closure Functions in PHP

Lambda functions in PHP are anonymous functions that can be stored in a variable or passed as an argument to other functions.

A closure is a type of lambda function that should be aware of its surroundings, but not every lambda is a closure .

Lambda requires a temporary function that will be used once.

Demonstrate How to Pass a Lambda Function as a Parameter in PHP

php $demo_array=array(4,3,1,2,8,9,3,10,5,13); //usort is a built-in PHP function to sort an array with a given condition.  usort($demo_array, function ($a, $b)   return ($a$b)?-1:1; >); // We passed an anonymous function that sorts the array in ascending order; this function is the lambda function.  foreach($demo_array as $val)  echo $val;  echo "
"
;
> ?>

usort() is a built-in PHP function that takes an array and a function as a parameter; the function should contain the condition on which you want to sort the array.

The code above tries to sort the array in ascending order with the help of the given lambda function.

Demonstrate How to Store a Lambda Function in a Variable in PHP

The other functionality of the lambda function in PHP can be stored in variables.

php $divide = function ($a, $b)   return $a / $b; >; echo $divide(10, 2); echo "
"
;
echo $divide(15, 2); echo "
"
;
echo $divide(10, 3); echo "
"
;
?>

The code above creates a lambda function that can divide two numbers and store them as variables. Now it can be used anywhere in the vicinity as a variable.

Difference Between Lambda and Closure Functions in PHP

Every closure function is a lambda function, but not every lambda is a closure function. A closure function needs to be aware of its surroundings.

php $range = range(10, 20); //Print the squared number from 10-20 range - an example of lambda.  echo "The output for lambda function: 
"
;
print_r(array_map(function($number) return $number**2; >, $range)); echo "

"
;
$power = 2; //Print a warning. print_r(array_map(function($number) return $number**$power; >, $range)); echo "

"
;
//Print the squared number from 10-20 range - an example of closure. echo "The output for closure function:
"
;
print_r(array_map(function($number) use($power) return $number**$power; >, $range)); ?>

The second example is we try to square the number through a variable, and it can’t; that is where the closure function comes.

We use the use keyword to pass the variable to the function. Now, this lambda function is a closure function.

The output for lambda function: Array ( [0] => 100 [1] => 121 [2] => 144 [3] => 169 [4] => 196 [5] => 225 [6] => 256 [7] => 289 [8] => 324 [9] => 361 [10] => 400 )  Notice: Undefined variable: power in C:\Apache24\htdocs\test.php on line 15 Array ( [0] => 1 [1] => 1 [2] => 1 [3] => 1 [4] => 1 [5] => 1 [6] => 1 [7] => 1 [8] => 1 [9] => 1 [10] => 1 )  The output for closure function: Array ( [0] => 100 [1] => 121 [2] => 144 [3] => 169 [4] => 196 [5] => 225 [6] => 256 [7] => 289 [8] => 324 [9] => 361 [10] => 400 ) 

The middle function cannot square the numbers because it cannot identify the outside variable. We pass the variable using the use keyword, and the lambda becomes a closure function.

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

Источник

Functions in PHP Tutorial

In this tutorial we learn about functions in PHP and how they help us break up our application logic into smaller sections for easy reuse throughout our code.

  • Functions
    • How to define a function
    • How to call (invoke) a function
    • How to define a function with arguments
    • How to use optional (default) parameters
    • How to use named parameters
    • How to use variable parameter lists
    • How to use variadic parameters
    • How to call a function in a loop
    • How to return a value from a function
    • Function return types
    • Callback functions
    • Closures
    • Arrow functions

    Functions

    As an application becomes bigger and more complex, we need ways to separate our code into smaller, reusable sections of logic. Functions are wrappers for those sections of logic.

    But they’re not just wrappers, they allow us to interact with the code inside to make a section of logic as reusable as possible.

    As an example, let’s consider the following code. It uses conditional control to evaluate if a number is even or odd.

       ""If we want to do the same evaluation on other numbers, we would have to rewrite the whole section of logic. To avoid this problem, we can wrap the logic inside a function.

    note We’ve used some built-in PHP functions earlier in the tutorial course, like the array() function.

    How to define a function

    A function can be simple or complex, based on the logic it contains. We will start with a simple function definition and add to its functionality as we go along.

    Functions in php consist of a minimum of 4 tokens.

    • The function keyword.
    • A descriptive identifier (name).
    • A parameter list wrapped with () (open & close parentheses).
    • A code block wrapped with <> (open & close curly braces).

    Inside the code block is where we write our section of logic.

     Functions are typically responsible only for a single task, which makes it easy to give them names. Our example below is responsible for alerting the user, so we can call it alertUser .
    To keep things simple for the moment, the logic is just an echo statement. But we can have conditional statements, loops, even other functions inside.

    How to call (invoke) a function

    At this point our function is defined, but we haven’t actually used it yet. To use a function we call it, which will execute the logic in the code block.

    To call a function all we need to do is reference the function name and the parameter list parentheses.

    note Even though we don’t have any parameters in our function yet, we still have to write the parentheses when calling the function.

      To demonstrate, let’s call the alertUser() function we defined earlier.
         If we run the example above in the browser, it will display the message that’s defined in the function’s code block.

    Once a function has been defined, we can use it anywhere in our script, even above the definition.

      The only exception to this is when a function is defined conditionally.
       Function names are case insensitive, but it’s good practice to always use the same case that the function was defined with.
      We covered PHP's casing conventions earlier in the course.

    Functions can be called as many times as we need.

     Each time the function is called, it will execute its logic.

    How to define a function with arguments

    We know from using the array() function that we can pass some values to a function through its parameter list.

    Parameters are temporary variables that we define and then use in the logic of the function’s code block. It’s similar to the temporary variable in a foreach loop.

    To create parameters, we specify them in the parameter list (between parentheses) when we define the function. If we use more than one parameter, we separate them with a commas.

      The parameters we define should be used somewhere in the logic. To demonstrate, let’s add a $user parameter to our function and use it in the echo statement.
    The value (argument) we pass to the funtion when it’s called will replace all the instances of $user in the logic.

    If a function contains a non-default parameter, we have to specify an argument for it when we call the function. Otherwise, the interpreter would raise an error.

    Output: Missing argument error

    Источник

Оцените статью