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?
use ($app)
. What is the difference between use-ing the $app
and passing it is a parameter?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.
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
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With