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

thomashysselinckx
thomashysselinckx
6,792 Points

use($app)

Hi guys, loving the tuts! I know it has been some videos, but I still haven't figured out why we have to put 'use($app)' after the function. I mean, the get or post keyword depends on the $app object already, isn't it?

Thanks for explaining!

3 Answers

Hey! This is more of a scoping-ee thing than anything else.

consider this:

<?php

$veryImportantName = 'Tom';

$importantPeople = array_filter($people, function($person) {
    return ($veryImportantName == $person['name'])
});

Now, array filter function accepts a callback as the second argument. You might've picked up scoping in previous videos. Essentially you can't use thing defined OUTSIDE of the function INSIDE the function. The above example would fail because inside that callback, $veryImportantName isn't accessible.

What you're doing is saying to the callback "HEY! There's this really cool variable I want to use inside you.".

It's handy because in a callback you can't add additional arguments. To make the above work, you'd need:

<?php

$veryImportantName = 'Tom';

$importantPeople = array_filter($people, function($person) use($veryImportantName) {
    return ($veryImportantName == $person['name'])
});

Check out the docs on anonymous functions

Hope this helps!

I figured this out answering a similar question. I don't think it is covered in the course.

use() is a built in function in PHP that allows aliasing and namespaces. It is the way that we tell PHP we want it to use whatever we assign to $app. In this example, we have assigned Slim.

thomashysselinckx
thomashysselinckx
6,792 Points

Thank you guys! Your answers made it clear to me now.