2017-07-06 78 views
1

我在Laravel控制器中有以下代码,但给定参数变量$ idea在'whereIn'函数中未定义。我如何在那里访问$ idea?谢谢!PHP Laravel功能变量范围

public static function getIdea($idea = null) { 
    if ($idea != "") { 
     return DB::table('test')->select('foo') 
      ->whereIn('bar', function($query) 
       { 
        $query->select('foobar') 
         ->from('bar2') 
         ->where('foo2', '=', $idea) 
         ->get(); 
       }) 
      ->get(); 
    } 
} 

回答

3

使用use关键字!参见Example#3继承父变量范围anonymous functions

public static function getIdea($idea = null) { 
    if ($idea != "") { 
     return DB::table('test')->select('foo') 
      ->whereIn('bar', function($query) use ($idea) 
       { 
        $query->select('foobar') 
         ->from('bar2') 
         ->where('foo2', '=', $idea) 
         ->get(); 
       }) 
      ->get(); 
    } 
} 
+0

该死的PHP:D非常感谢你,就是这样。 – Hillcow