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

7

I wonder, what is 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?

    
asked by anonymous 22.05.2015 / 23:02

2 answers

8

The first is an incognito , while the second is only a function set 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);

View demonstração

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

Example:

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

array_map($funcao, $frutas);

View demonstração

    
22.05.2015 / 23:38
7

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

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

Anonymous functions were introduced in version 5.3 of PHP. They are usually used as callbacks, that is, passed directly to another function, which executes them when (or if) is required.

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 that it is passed to preg_replace_callback , and executed for each match found for the regular expression in the input text ( 'hello-world' ).

    
22.05.2015 / 23:38