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" 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

?>