Skip to content
Advertisement

Undefined variable ‘count’

I haven’t done PHP in a while so I’m a bit confused why I am getting the error in the title

$count =0;
User::chunk(200, function ($users) {
    $count++;
    error_log('------------ chunck: '.$count);
});

Advertisement

Answer

You have to use use, described in docs(http://php.net/manual/en/functions.anonymous.php):

Closures may also inherit variables from the parent scope. Any such variables must be declared in the function header. Inheriting variables from the parent scope is not the same as using global variables. Global variables exist in the global scope, which is the same no matter what function is executing.

Code:

$count =0;
User::chunk(200, function ($users) use($count) {
    $count++;
    error_log('------------ chunck: '.$count);
});
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement