What is the purpose of the "use" command and what is its relation to anonymous functions?

10

I'm doing tests with a RESTFul API that I'm creating using the Slim micro-framework, and in one of those routines that is responsible for executing a particular action, I was struck by a command I did not know, which is the command use .

Below is an example of the command use in a method that returns a JSON with the data obtained from the database:

//Listando todas pessoas
$app->get('/pessoas/', 
        function() use ($app) 
        {
            (new \controllers\Pessoa($app))->listar();            
        });

This command seems to be part of the anonymous function function() that is responsible for the route:

http://localhost/RestApiEx/pessoas/

And the use of it left me with the following doubts.

Questions

I would like to know what is the purpose of the use command and what is the relation it has with anonymous functions?

    
asked by anonymous 18.12.2016 / 01:40

1 answer

8

The use passes the value of one or more variables to the scope of the anonymous function making this value accessible (inheriting the variable), for example if you do this:

<?php

$a = 'Olá, mundo!';

$foo = function() {
   echo $a;
};

$foo();

You will acknowledge that the variable has not been defined, something like:

  

PHP Notice: Undefined variable: a in example.php on line 6

But if you do this:

<?php

$a = 'Olá, mundo!';

$foo = function() use ($a) {
   echo $a;
};

$foo();

It will print the value 'Olá, mundo!'

In the Slim framework the main application variable is $app , but to make it accessible to the scope of the anonymous function, use is required, if you do this:

$app->get('/pessoas/', 
        function() 
        {
            (new \controllers\Pessoa($app))->listar();            
        });

You would have a similar error:

  

PHP Notice: Undefined variable: app in example.php on line 9

And your controller would get a value null instead of the object new \Slim\App;

Doc: link

Extras

  • One detail, while using use , the example% variable is not a reference , if you do something like this:

    <?php
    
    $a = 1;
    
    $foo = function() use ($a) {
       $a += 10;
    };
    
    $foo();
    
    echo $a;
    

    It will be displayed:

      

    1

    But if you refer:

    <?php
    
    $a = 1;
    
    $foo = function() use (&$a) {
       $a += 10;
    };
    
    $foo();
    
    echo $a;
    

    11 will be displayed:

      

    11

  • Something important to note is that in PHP there is another $a , which is used to create class aliases, like this:

    <?php
    
    use Foo\Bar\Baz; //é possivel chamar new Baz, sem o namespace completo
    use Foo\Bar\Baz as Test; //é possivel chamar new Test para se referir ao Foo\Bar\Baz
    

    Read more at link

  • 18.12.2016 / 02:00