THE FUNCTIONS IN PHP

FUNCTIONS AS A LEVEL OF ABSTRACTION

php logoSuppose we want to define three sequences as shown in the code below. This code in general could be fine, only that every time we want to get this functionality we have to rewrite the low-level code. But we can create a level of abstraction thanks to functions. showSequence abstracts the 3 previously created loops. We create a library and bring the function into lib.php. We achieved the same result by adding a level of abstraction and the resulting code is much cleaner.

Abstract Function
Abstract Functionality

CALLBACK AND HIGHER ORDER FUNCTIONS

A function can be assigned to a variable and passed to another function. We work with functions as we do with any value passed in input. A function passed as input to another is called a callback. Let’s take an example immediately (REFERENCE CODE BELOW). If we want to do type hinting we must indicate the parameter as callable or closure if the function is anonymous. A function that receives another function such as fn1 as input is called a higher-order function. With the higher order functions we can perform an abstraction on the actions, i.e. as regards the printing of a sequence from an initial number to a final number we carried out an abstraction on the values, i.e. the values shown as a sequence were indicated in the invocation phase of the function. With higher-order functions we do not define the behavior of the function itself.

HIGHER ORDER FUNCTIONS

fn2 will do the callback by passing the array $ a as input. But fn2 does not actually know the behavior of the callback it will invoke, that is, what will be done on the $ a array is something defined within the callback itself. We can define an anonymous function but also a normal function, sumEven e sumEven. If we use closure before the parameter $cb we have a fatal error, this is because argument two must be of type closure while we have specified a string. A closure is an anonymous function, having not defined anonymous functions we must indicate as type hinting callable. The action determined on the array does not lie in the higher-order function fn2, but is determined by the function we pass as the second argument. In this way we have performed an abstraction on the action. Let’s go to the browser and go to this address: https://www.php.net/manual/en/function.usort usort sorts an array by value using a user-defined function. See this example to learn more and better understand higher order functions.

Copy to Clipboard

ARROW FUNCTION

Arrow functions are an improvement of the syntax of anonymous functions. to define an arrow function we have to put fn in place of function , and an arrow instead of staples. The return statement is removed. They do not have their own scope, within an arrow function it is possible to access the global scope.

Copy to Clipboard

FURTHER INFORMATION

Callback Functions in PHP

Callback functions in PHP are functions that are passed as arguments to another function and then executed within that function.
This concept is common in many programming languages, especially in languages that support functional programming.

Example of Callback Function

Suppose we have a calling function that takes another function as its argument:

function caller(callable $callback) {
// execute the code before the callback

echo“Before callback\n“;
// call the passed function

$callback();

// executes the code after the callback

echo“After callback\n“;

}

function example() {
      echo“This is the callback function\n“;
}

// We pass the function ‘example’ as a callback

caller(‘example‘);

In this example, the function example is passed as a callback to the calling function. Inside caller, example is executed.

Anonymous Callback Functions

PHP also allows anonymous functions (i.e., unnamed functions) to be used as callbacks. Anonymous functions are also known as closures. This allows a function to be defined directly at the time of the call:

caller(function() {

       echo“This is an anonymous callback function“;

});

Callback with Parameters

It is possible for a callback function to accept parameters:

function caller(callable $callback, $parameter) {
    echo“Before callback\n“;
    $callback($parameter);
    echo“After callback\n“;
}

function example($name) {
      echo“Hello, $name.”
}

caller(‘example‘,‘Mario‘);

Here, the example function accepts a parameter $name and prints it. This parameter is passed by the calling function.

ARROW FUNCTION.

Arrow functions in PHP are a syntax introduced starting with PHP 7.4 to create anonymous functions in a more concise and readable way. This syntax is similar to that used in other languages such as JavaScript.

Here is a description of the main features of arrow functions in PHP:

1. Concise syntax: Arrow functions are defined using the syntax fn, followed by the parameters in round brackets, an arrow (=>), and then the expression that forms the body of the function.

$sum = fn($a, $b) => $a + $b;

In this example, $sum is an anonymous function that takes two parameters $a and $b and returns their sum.

2. Implicit return: Unlike normal anonymous functions (created with function), arrow functions do not require the use of the return command to return a value. The expression after the arrow (=>) is automatically returned.

3. Inherited scope: Arrow functions automatically inherit the scope (scope) of the variable from the function or context in which they are defined. This means that there is no need to use use to import variables into the function’s scope.

$multiplier = 2;
$double = fn($n) => $n * $multiplier;

echo $double(5); // Output: 10

In this example, the arrow function $double can access the variable $multiplier directly, without the need to declare it explicitly with use.

4. Limitations: Arrow functions in PHP can only contain a single expression, so they cannot have a function body with multiple instructions or complex code blocks. For more complex functions, you still have to use traditional anonymous functions or normal functions defined with function.

Arrow functions offer a more elegant and compact way to define simple functions and are mainly used when working with callbacks or higher-order functions (e.g., array_map, array_filter, etc.)

Lambda Functions in PHP

Lambda functions in PHP are, in essence, a type of anonymous function.
They are often used when you need a function that is used only once or passed as an argument.

Creating a Lambda Function

A lambda function can be defined in this way:

$sum = function($a, $b) {
return $a + $b;
};

echo $sum(2, 3); // Print: 5

Here, $sum is a variable that contains an anonymous function. This function can be called like a normal function.

Using External Variables in a Lambda

Lambda functions in PHP can access external variables using the use keyword:

$factor = 2;
$multiply = function($number) use ($factor) {
        return $number * $factor;
};

echo $multiply(5); // Print: 10

In this case, the variable $factor is external to the lambda function, but is made accessible within the function thanks to use ($factor).

Differences between Callback and Lambda

1.Usage:

-Callbacks are primarily used to pass a function to be executed later (e.g., within a loop or library function).

-Lambdas are anonymous functions that can be used in contexts where a function is needed only temporarily.

2. Syntax:

-Callbacks can be passed as function names, object methods, or anonymous functions.

-Lambdas are always anonymous functions.

3. Flexibility:

-Callbacks are more generic and can include references to existing functions.

-Lambdas are specifically useful for situations where a function is required ad hoc and is not reused elsewhere.

Practical Examples

Sorting with a Callback Function

One of the most common examples of the use of callback functions in PHP is the sorting of custom arrays:

$array =[3, 2, 5, 6, 1];

usort($array, function($a, $b) {
return $a <=> $b;
});

print_r($array);

In this example, the anonymous function specifies how to sort the array elements.

Conclusion

Callback functions and lambdas offer powerful flexibility in PHP programming. Callbacks allow you to separate main logic from specific behavior, while lambdas allow you to define temporary functions concisely and clearly. These tools are essential for writing modular and reusable PHP code.

LINKS TO PREVIOUS POSTS

THE PHP LANGUAGE

LINK TO THE CODE ON GITHUB

GITHUB