title: Non-local variables in a PHP Collection Class method
body: <p>I was looking into implementing a collection class into my PHP application, however, I had some questions about using the class.</p>
  
  <p>I am basing some of my methods on the Laravel Collection Class (<a href="https://laravel.com/docs/5.2/collections" rel="nofollow">https://laravel.com/docs/5.2/collections</a>).</p>
  
  <p>If I am using the .each method:</p>
  
  <pre><code>public function each($callback)
  {
      foreach ($this-&gt;items as $key =&gt; $item) {
          if ($callback($item, $key) === false) {
              break;
          }
      }
  
      return $this;
  }
  </code></pre>
  
  <p>How can I use non-local variables in the callback? For example, I have a courses collection and a users collection.</p>
  
  <pre><code>$courses = new Collection($this-&gt;getCourses());
  $users = new Collection($this-&gt;getUsers());
  
  // I need to loop through all courses and within each course, loop through   
  // all users
  $courses-&gt;each(function($course, $courseKey) {
  
      // How can I make it so $users is available here?
  
      $users-&gt;each(function($user, $userKey) {
  
          // How can I make it so $course is available here?
  
          // ...
      });
  });
  </code></pre>
  
  <p>Is what I am trying to accomplish a bad practice? Should I use the <code>global</code> keyword or is that also bad practice?</p>