如果在each()函数内调用外部变量,会发现直接报变量不存在的错误
$rows = empty($where['limit']) ? Config::get('paginate.list_rows') : $where['limit'];
if(!empty($where['limit'])) {
unset($where['limit']);
}
$tmp = 111;
$list = self::
field('umo.*,u.nickname,u.account')
->alias('umo')
->join('user u','umo.user_id=u.id','left')
->order('umo.id desc')
->where($where)
->paginate($rows,false,['query'=>$where])->each(function($item){
dump($tmp);
$item['typename'] = UserMoneyLog::getType()[$item['type']];
})->toArray()?:[];
return $list;
然后我觉得是变量作用域问题,于是在each()里加了个global声明
$rows = empty($where['limit']) ? Config::get('paginate.list_rows') : $where['limit'];
if(!empty($where['limit'])) {
unset($where['limit']);
}
$tmp = 111;
$list = self::
field('umo.*,u.nickname,u.account')
->alias('umo')
->join('user u','umo.user_id=u.id','left')
->order('umo.id desc')
->where($where)
->paginate($rows,false,['query'=>$where])->each(function($item){
global $tmp;
dump($tmp);
$item['typename'] = UserMoneyLog::getType()[$item['type']];
})->toArray()?:[];
return $list;
虽然不报变量不存在了,但是打印出来的值是null,还是没有调用到外面的变量
最后,在each()函数后调用一个use函数,即可传参成功
$rows = empty($where['limit']) ? Config::get('paginate.list_rows') : $where['limit'];
if(!empty($where['limit'])) {
unset($where['limit']);
}
$tmp = 111;
$list = self::
field('umo.*,u.nickname,u.account')
->alias('umo')
->join('user u','umo.user_id=u.id','left')
->order('umo.id desc')
->where($where)
->paginate($rows,false,['query'=>$where])->each(function($item) use($tmp)/*添加的参数*/{
dump($tmp);
$item['typename'] = UserMoneyLog::getType()[$item['type']];
})->toArray()?:[];
return $list;
如果在函数中需要修改变量的值,会发现在函数内,变量的值改变了,但是函数外面的变量值还是没变
$rows = empty($where['limit']) ? Config::get('paginate.list_rows') : $where['limit'];
if(!empty($where['limit'])) {
unset($where['limit']);
}
$tmp = 111;
$list = self::
field('umo.*,u.nickname,u.account')
->alias('umo')
->join('user u','umo.user_id=u.id','left')
->order('umo.id desc')
->where($where)
->paginate($rows,false,['query'=>$where])->each(function($item) use($tmp){
$tmp = $tmp + 1;
dump($tmp. '"tmp1"');
$item['typename'] = UserMoneyLog::getType()[$item['type']];
})->toArray()?:[];
dump($tmp . '"tmp2"');
return $list;
$rows = empty($where['limit']) ? Config::get('paginate.list_rows') : $where['limit'];
if(!empty($where['limit'])) {
unset($where['limit']);
}
$tmp = 111;
$list = self::
field('umo.*,u.nickname,u.account')
->alias('umo')
->join('user u','umo.user_id=u.id','left')
->order('umo.id desc')
->where($where)
->paginate($rows,false,['query'=>$where])->each(function($item) use(&$tmp){
$tmp = $tmp + 1;
dump($tmp. '"tmp1"');
$item['typename'] = UserMoneyLog::getType()[$item['type']];
})->toArray()?:[];
dump($tmp . '"tmp2"');
return $list;