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 Building Websites with PHP Slim Basics & Twig Templates Including & Running Slim

Why 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');
    });

The 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.

1 Answer

It 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.