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 trialLogan Call
20,406 PointsWhy does the 'get' method of the 'Slim' instance (app), require the 'use' function in order to reference app? Redundant?
It just seems redundant. I understand it's necessary to use the 'use' function to allow closures to use variables outside their scope, but wouldn't the Slim instance be within it's own scope??
code I'm referring to...
$app = new \Slim\Slim();
$app->get('/', function() use($app) {
$app->render('index.html');
});
$app->get('/contact', function() use($app) {
$app->render('contact.html');
});
1 Answer
Ted Sumner
Courses Plus Student 17,967 PointsIt is clearly not redundant because the code does not work without it. I wish I could explain it, but I don't really know the answer for sure but some quick research and think I know the answer.
use()
is an internal PHP function. http://php.net/manual/en/language.namespaces.importing.php
As such, Slim does not have anything to do with it directly. So to utilize Slim, you need to alias Slim to a variable and use the variable as the argument for the use() method.
Antonio Jaramillo
15,604 PointsAntonio Jaramillo
15,604 PointsThe callback function is an anonymous function that wouldn't know what to do with an undefined $app variable. By using the use() method and passing $app as a parameter, you are telling this anonymous function what to do with the Slim object we created above. In Slim 3, however, we can now use $this without having to implement use() because callback functions in our get method now recognize $this a pointing to $app itself.