Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP PHP Functions Function Returns and More PHP Closures

Aakash Srivastava
Aakash Srivastava
5,415 Points

PHP Closures

Is there a difference between two of these functions:

<?php

function add_up(){

}

$add_up = function(){

};

3 Answers

Tim Stride
Tim Stride
12,827 Points

Yes, assuming the same function is being defined within the {} in each, I believe both would do the same thing. The second is an anonymous function (no function name has been defined for it) so you would call it in your code by echoing the variable name that contains it.

More detail here

jamesjones21
jamesjones21
9,260 Points

there are differences between the two, in javascript when you assign a function to a variable, they are known as anonymous functions (functions with no names). With a normal function declaration there are no semi colons after the end curly brace and a name is provided to the function. PHP works exactly the same :)

See some examples below:

PHP

<?php

$myVariable = function($string){
    echo $string;   
};


//outputs testing 
$myVariable('testing');

JS

var myVar = function (string){ 
document.write(string); 
};

myVar('testing');

hope this helps

Tim Stride
Tim Stride
12,827 Points

As James said, there is a difference in how the normal function and the anonymous function are written

when you assign a function to a variable, they are known as anonymous functions (functions with no names). With a normal function declaration there are no semi colons after the end curly brace and a name is provided to the function.

but both will output the same thing if the same string is passed through. I've added to James' example below to show this. Both will output 'testing' on to the page (or whatever string you want to pass through the function).

<?php

// function with no name, assigned to a variable (anonymous function):

$myVariable = function($string){
    echo $string;   
};


//outputs testing 
$myVariable('testing');


// normal function with a name:

function myVariable($string) {
    echo $string;

}

//outputs testing
myVariable('testing');

?>