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 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->get('/contact', function() use($app) {

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.