Closures in PHP
Like JavaScript, PHP as well has anonymous functions, also referred to as closures
(while related, not the same as closures in functional programming). I first came across anonymous functions in JavaScript, but recently learned about their PHP counterpart while playing around with Slim, a PHP framework not unlike Sinatra, which I ♥. Closures are an important part of route declarations in Slim:
1 2 3 4 5 6 |
|
The application that I am building on Slim uses Doctrine ORM. The ORM handles object retrieval through the EntityManager
class. Using a call to EntityManager
, I can access my objects and then be able to use them within my application.
1 2 3 4 |
|
I still needed a way to pass the instance of EntityManager
to my Slim routes. One way, of course, would be to make this instance a global
variable. While useful, global
variables are not the cleanest way to code. I might not want every function in my application to have access to this variable.
However, closures in PHP can inherit variables from the parent scope in a much more controlled and cleaner way with the use
construct. The parent scope of the closure is where the closure is declared, and lucky for me, my code is organized as such that my $entityManager
declaration lives in that same scope.
1 2 3 4 5 6 7 8 9 |
|