如何将变量“$ tid,$ id”传递给原始函数?

时间:2015-02-18 05:22:49

标签: mongodb laravel-4 php-5.2

当我在原始函数中调用$id$tid来从mongodb集合的子文档中获取某些数据时,它会显示错误these two variables are undefined($tid,$id)

<?php
$id=IntValue;
$tId=IntValue;
if($tId==0)
{
    $maxPlayers=0;
}
else
{
  $result = DB::collection('PrizeDistributionTemplate')->raw(function($collection)
        {

            return $collection->aggregate(array(
                array(
                    '$match' => array( 'id' => $id,'templates.tId' => $tid)
                ),
                array( '$unwind' => '$templates' ),
                array(
                    '$match' => array( 'id' => $id,'templates.tId' => $tid)
                ),
            ));       
        });

  $result=json_decode(json_encode($result),true);
  $maxPlayers=$result['result'][0]['templates']['maxPlayers'];
  $maxPlayers=intval($maxPlayers)+2;
}
?>

2 个答案:

答案 0 :(得分:1)

当你在PHP中使用回调函数时,函数就像它拥有的范围一样,并且不能从它的范围之外访问变量。

$foo = true;

DB::collection('something')->raw(function ($collection) {
    echo $foo;// $foo is undefined here, this create an error
});

echo $foo;// here it work

但您可以使用PHP use keyword

为变量提供回调
$foo = true;

DB::collection('something')->raw(function ($collection) use ($foo) {
    echo $foo;// now it works
});

答案 1 :(得分:0)

它可以很好地添加批量,这样你只需要在数组上创建并传递它。

$temp = [
   [
     'item' => "envelopes"
   ],
   [
     'item' => "envelopesas"
   ],
   [
     'item' => "lala"
   ]
 ];

 $userData = DB::table('log') - > raw(function ($collection) use($temp) 
 {

   return $collection - > insertMany($temp);
 });