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
<?php
//taken from the Slim Documentation:
$app->get('/hello/:name', function ($name) {
    echo "Hello, $name";
});
?>

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
<?php
// obtaining the entity manager; $conn is my database access and $config is my model configuration
$entityManager = EntityManager::create($conn, $config);
?>

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
<?php
$app->get('/topics', function() use($entityManager) {
  $dql = "SELECT t, u FROM Topic t JOIN t.user u ORDER BY t.id DESC";
  $query = $entityManager->createQuery($dql);
  $topics = $query->getResult();

  //I'm dynamically doing things with my $topics here
});
?>

Comments