Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined variable 'count'

Tags:

php

laravel

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);
});
like image 644
code511788465541441 Avatar asked May 31 '26 12:05

code511788465541441


1 Answers

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);
});
like image 57
MoeinPorkamel Avatar answered Jun 03 '26 02:06

MoeinPorkamel