What is the difference between $var = Function() and Function var()?

Asked

Viewed 129 times

8

I’d like to know, what’s the difference between:

<?php

$var = function() {
    return 5;
}

$var();

and...

<?php

function var() {
    return 5;
}

var();

What would be the difference between them? When to use them?

  • John Paul, is there anything else that can be improved in any of the answers?

  • 1

    No. Everyone responded clearly and simply to me. Thank you!

2 answers

9


The first is a anonymous function, while the second is only one defined function by the user.

Anonymous functions are useful in situations where you need to use a return function, callback, see an example:

$frutas = array('Maça', 'Banana', 'Perâ', 'Morango');

$funcao = function($fruta) {
    echo $fruta . "\n";
};

array_map($funcao, $frutas);

See demonstração

Note: This is valid if you have PHP 5.3 or higher in previous versions, consider using the function create_function.

Example:

$frutas = array('Maça', 'Banana', 'Perâ', 'Morango');
$funcao = create_function('$fruta', 'echo $fruta . "\n";');

array_map($funcao, $frutas);

See demonstração

7

What you have in the first example is a anonymous function, which is assigned to the variable $var and then invoked. The variable has a name, but the function itself does not have.

In the second case, var is the name of the function (but I think it is an illegal name, since "var" is a reserved word of language). Apart from this problem, his second example is what is considered a common function, the kind that has always existed in language.

Already anonymous functions have been introduced in PHP version 5.3. They are usually used as callbacks, that is, passed directly to another function, which executes them when (or if) it is necessary.

Example (from the manual):

echo preg_replace_callback('~-([a-z])~', function ($match) {
    return strtoupper($match[1]);
}, 'hello-world');
// outputs helloWorld

The anonymous function is declared at the same time it is passed to the preg_replace_callback, and executed for each match found for the regular expression in the input text ('hello-world').

Browser other questions tagged

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