How do callbacks and anonymous functions work in PHP?

Asked

Viewed 171 times

1

Good afternoon,

  1. How an anonymous PHP function works?

  2. How does the callback in PHP?

  3. How to work the two together? (anonymous and callback)

    I studied a little Javascript and found it very different in PHP to apply these callback, seem to be more complex than in Javascript, could give me a definition and examples, as I consulted the documentation (https://www.php.net/manual/en/class.closure.php) and I didn’t really understand.

1 answer

1

As anonymous functions PHP works similarly as function expressions (Function Expression) javascript.

To anonymous function is usually used as a callback but is not restricted to this, it can also be used in specific cases of your code, for example:

Perform a specific behavior within a function that will be useful only for this scope.

$addition = function($num1, $num2) {
    return $num1 + $num2;
};

echo $addition(5, 5); //10

To Callback is the use of a function as a parameter of another function, allowing the use of callback as soon as necessary. A good example of using a callback is the function array_map.

public function getFilename()
{
    $files = ['wallpaper', 'user-photo', 'nude'];

    $appendJpg = function($name) {
        return $name . '.jpg';
    };

    $filesJpg = array_map($appendJpg, $files);

    print_r($filesJpg); //Array ( [0] => wallpaper.jpg [1] => user-photo.jpg [2] => nude.jpg )
}

Anonymous functions implemented from the PHP 5.3 version produce objects of the type Closure which offers methods for handling the function. A Closure allows inheriting variables from the parent scope (scope of the function where closure is declared) using the instruction use.

$name = 'Victor';

$fullName = function($lastName) use ($name) {
    return "$name $lastName";
};

echo $fullName('Carnaval'); //Victor Carnaval

Browser other questions tagged

You are not signed in. Login or sign up in order to post.