124697
124697

Reputation: 21893

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);
});

Upvotes: 2

Views: 1772

Answers (2)

ScaisEdge
ScaisEdge

Reputation: 133360

you should use use ($count) for pass the var $count to the anonymous function

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

see more here http://php.net/manual/en/functions.anonymous.php

Upvotes: 4

MoeinPorkamel
MoeinPorkamel

Reputation: 711

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);
});

Upvotes: 5

Related Questions