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