Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP PHP Functions Function Returns and More PHP Closures

Why use 'use' when we can just pass the variable into the actual function?

<?php

$name = 'Mike';

$greet = function($name){ echo "Hello, $name!"; };

$greet();

VS

<?php

$name = 'Mike';

$greet = function() use($name){ echo "Hello, $name!"; };

$greet();

1 Answer

Kevin Korte
Kevin Korte
28,109 Points

Because you can't always pass in all the variables you need into a function.

First, there is a small error to correct.

It should be

$name = 'Mike';

$greet = function($name){ echo "Hello, $name!"; };

$greet($name);

Otherwise, $greet doesn't know what you're passing to it.

With that side, this is using the concept of closure. The second example, is passing a copy of the variable from outside it's scope into the variable.

Take for instance, you wanted to use array_walk(). http://php.net/manual/en/function.array-walk.php The callback typically only allows 2 parameters. If you need more than two parameters passed into the function, you could use the use closure to pass a copy of those variables in so you could do whatever you needed to do.

I think this is helpful: http://stackoverflow.com/questions/10692817/whats-the-difference-between-closure-parameters-and-the-use-keyword