【问题标题】:how to pass variables "$tid, $id" into raw function?如何将变量“$tid, $id”传递给原始函数?
【发布时间】:2015-04-19 00:51:20
【问题描述】:

当我在原始函数中调用 $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;
}
?>

【问题讨论】:

    标签: mongodb laravel-4 php-5.2


    【解决方案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
    });
    

    【讨论】:

      【解决方案2】:

      它非常适合批量添加,这样你只需要在数组上创建并传递它。

      $temp = [
         [
           'item' => "envelopes"
         ],
         [
           'item' => "envelopesas"
         ],
         [
           'item' => "lala"
         ]
       ];
      
       $userData = DB::table('log') - > raw(function ($collection) use($temp) 
       {
      
         return $collection - > insertMany($temp);
       });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-02-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-24
        • 2016-01-13
        • 2020-12-20
        相关资源
        最近更新 更多