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

Why use "use" and not an argument?

<?php

$name = "Mike";

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

$greet();

?>

both result in the same output...

<?php

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

$greet("Mike");

?>

Hello Colby,

i asked a friend of mine some time ago "What do you PHP guys need 'use' for anyway?". Because i personally think its quite ugly. Javascript uses a concept like this to simulate its "classes". But I really didn't expect PHP to have such a thing.

He told me that normally he circumvents this, but there are inversion of control containers for PHP. And the sources of those are full of "use", to construct factories.

Best regards, Stefan

2 Answers

In the real world, I've used 'use' for functions like array_filter where you can't define the arguments of the callback. This isn't a great example, but hopefully it gives you a little insight.

<?php
$flavors = ['vanilla', 'chocolate', 'strawberry', 'raspberry'];

$favorites = ['vanilla', 'chocolate'];

$favoriteFlavors = array_fitler($flavors, function($flavor) use ($favorites) {
    return in_array($flavor, $favorites);
})

$favoriteFlavors // ['vanilla', 'chocolate'];

Because 'use' keyword uses the value of variable at the time of closure definition, whereas function argument gets the latest value of variable, no matter what it was at the time of definition.

Change your first example to:

<?php

$name = "Mike";

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

$name = "Tom";

$greet(); // Mike

?>

and change your second example to:

<?php

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

$name = "Tom";

$greet($name); // Tom

?>