Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between "use" and passing a parameter to controller function

I don't have a specific problem, just looking to deepen my understanding of what's going on with Silex and with some new-ish PHP features in general. This is based off the code samples on the "usage" page of the Silex documentation:

$blogPosts = array(
    1 => array(
        'date'      => '2011-03-29',
        'author'    => 'igorw',
        'title'     => 'Using Silex',
        'body'      => '...',    );

$app->get('/blog/{id}', function (Silex\Application $app, $id) use ($blogPosts) {
    //do stuff
}

Questions

  • What is the difference here between passing the $app and $id as parameters to the function, and use-ing the $blogPosts variable?

  • Could $blogPosts also have been passed as a parameter to the function?

  • Also, I more commonly see use ($app). What is the difference between use-ing the $app and passing it is a parameter?
like image 380
patricksayshi Avatar asked Apr 06 '13 14:04

patricksayshi


2 Answers

This has nothing to do with silex and everything to do with "some new-ish PHP features". You are creating an anonymous function (also called a closure), reusable several times with different $app and $id values, BUT with only the same $blogPosts value.

<?php
$a = "a";
$b = "b";
$c = function ($d) use ($b) {
    echo $d . "." . $b . PHP_EOL;
};
$b = "c";
$e = function ($d) use ($b) {
    echo $d . "." . $b . PHP_EOL;
};

$c($a); // prints a.b, and not a.c
$e($a); // prints a.c

Here, i'm building a function with $b, and once it is build, I use it with variables that do not have to be named the same way the function's argument is named.

like image 135
greg0ire Avatar answered Sep 28 '22 01:09

greg0ire


Maybe this makes it more transparent

<?php
$a = "a1";
$b = "b1";
$f = function ($x) use ($b) {
    echo $x . $b;
};
$f($a); // prints a1b1

// now let's change values of $a and $b
$a = "a2";
$b = "b2"; //--> won't be used as $b was 'b1' when declaring the function.
$f($a); // prints a2b1
?>
like image 34
simUser Avatar answered Sep 28 '22 00:09

simUser