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

Question:

I would like to know, what is the difference between:

<?php

$var = function() {
    return 5;
}

$var();

e…

<?php

function var() {
    return 5;
}

var();

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

Answer:

The first is an anonymous function , while the second is just a user- defined function .

Anonymous functions are useful in situations where you need to use a callback function , 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, on earlier versions, consider using the create_function function.

Example:

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

array_map($funcao, $frutas);

View demonstração

Scroll to Top