title: How to reference this in closure
body: <p>I am using PHP Version 7.1.1.</p>
  
  <p>In <code>index.php</code> of my MVC I create a route collection (<code>$routes</code>). To it I want to add a route group (with <code>addGroup</code>). This addition process relies on a closure (e.g. an anonymous function), passed as argument to <code>addGroup</code>. Inside of closure <strong>I am trying to reference the collection with <code>$this</code></strong>, so that I can add one or more routes to it (with <code>addRoute</code>, a method of the collection).</p>
  
  <p>Unfortunately I could not achieve that, although I made some tries. I miss a piece of the closures theory, somewhere. I would appreciate, if you would provide me an advice.</p>
  
  <p>The "problem" is, that, in order to achieve a simplified usability for the user, I am trying to avoid the direct use of a closure parameter. Why? Because inside <code>addGroup</code> I am already in the collection's scope and from there I am calling the closure. This way I can pass the collection's instance (<code>$this</code>) as argument to the <code>executeGroupHandler</code> method and, therefore to <code>executeGroupHandler</code> as well.</p>
  
  <p>Thank you for your time and patience!</p>
  
  <hr/>
  
  <h3>index.php</h3>
  
  <pre><code>$routes = new RouteCollection();
  
  $routes-&gt;addGroup('/test', function() {
      $this-&gt;addRoute('GET', '/group', function() {
          echo 'Hello from route /test/group';
      });
  });
  </code></pre>
  
  <h3>RouteCollection</h3>
  
  <pre><code>class RouteCollection implements CollectionInterface {
  
      public function addGroup(string $groupPattern, callable $groupHandler) {
          $group = new RouteGroup($groupPattern, $groupHandler);
  
          return $group-&gt;executeGroupHandler($this);
      }
  
      public function addRoute($httpMethod, string $routePattern, $routeHandler) {
          //...
          return $this;
      }
  
  }
  </code></pre>
  
  <h3>RouteGroup</h3>
  
  <pre><code>class RouteGroup {
  
      private $groupPattern;
      private $groupHandler;
  
      public function __construct(string $groupPattern, callable $groupHandler) {
          $this-&gt;groupPattern = $groupPattern;
          $this-&gt;groupHandler = $groupHandler;
      }
  
      public function executeGroupHandler(CollectionInterface $routeCollection) {
          return call_user_func_array($this-&gt;groupHandler, [$routeCollection]);
      }
  
  }
  </code></pre>