不在对象上下文中时使用$ this - Laravel 4

时间:2013-11-28 10:06:15

标签: php scope laravel this

我在Contact.php模型中有这两种方法:

public function getSubscribers($listId)
{
    return $this->withTrashed()
        ->where(DB::raw("concat('',email * 1)"), '!=', DB::raw('email'))
        ->where('opt_out', '0')
        ->select('email')
        ->chunk(1000, function($results) use ($listId) { $this->subscribeEmails($listId, $results); });
}

public function subscribeEmails($listId, $subscribers)
{
    $emails = array();

    foreach ($subscribers as $key => $subscriber)
    {
        $memberActivity = $subscriber->memberActivity($listId);

        if ( ! $memberActivity['data'])
        {
            $emails[] = array('email' => $subscriber->email);
        }
        else
        {
            foreach ($memberActivity['data'] as $data)
            {
                foreach ($data['activity'] as $activity)
                {
                    if ($activity['action'] !== 'unsub')
                    {
                        $emails[] = array('email' => $subscriber->email);
                    }
                }
            }  
        }
    }

    MailchimpWrapper::lists()->batchSubscribe($listId, $emails, false, true);
}

通过名为updateMailchimp()的方法在我的AdminContactsController.php控制器中调用getSubscribers()方法:

public function updateMailchimp()
{
    $this->contact->getSubscribers($this->listId);

    $message = (object) array(
        'title'         => 'Excellent!',
        'content'       => 'The Mailchimp newsletter list has been updated with the latest contacts from within the system.',
        'alert_type'    => 'success'
    );

    return Redirect::back()->with('message', $message);
}

在本地,这很好,除了在登台服务器上没有任何问题,我得到以下错误引用行cotaining - > chunk(1000,function($ results)use($ listId){$ this-&gt ; subscribeEmails($ listId,$ results);});:

Using $this when not in object context

这是PHP版本问题还是我在这里遗漏了什么?

1 个答案:

答案 0 :(得分:2)

您的代码在localhost上工作但在远程服务器上工作的原因可能与PHP版本不同。在PHP 5.4.0之前 it is not possible to use $this from anonymous function 。您必须将$this关键字中的引用传递给use

public function getSubscribers($listId)
{
    $that = $this; // <---- create reference to $this
    return $this->withTrashed()
        ->where(DB::raw("concat('',email * 1)"), '!=', DB::raw('email'))
        ->where('opt_out', '0')
        ->select('email')
        ->chunk(1000, function($results) use (&$that, $listId) { $this->subscribeEmails($listId, $results); });
}