Search code examples
phpanonymous-functionscoping

How to pass out of scope variables to anonymous function


I am new in PHP.

I want to create a function link this.

public static function cat_post($category, $limit, $top)
{
    $posts = Post::whereHas('categories', function($q)
        {
            $q->where('name', 'like', $name);
            $q->where('top', 'like', $top);

        })->take($limit)->get();
}

But i got

Undefined variable "name"

Please help me. How to create this function....


Solution

  • use as below:

    public static function cat_post($category, $limit, $top)
    {
        $posts = Post::whereHas('categories', function($q) use ($name, $top)
            {
                $q->where('name', 'like', $name);
                $q->where('top', 'like', $top);
    
            })->take($limit)->get();
    }
    

    have a look here