Using $this when not in object context - Laravel 4

laravel, php, scope, this

Solution

The reason why your code works on localhost but not on the remote server is probably the difference in PHP versions. Before PHP 5.4.0 it is not possible to use $this from anonymous function. You must pass the reference to `$this` within the `use` keyword:

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); });
}

Problem

I have these two methods in my Contact.php model: ``` 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); } ``` And the getSubscribers() method is called in my AdminContactsController.php controller via a method called updateMailchimp(): ``` 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); } ``` Locally, this works great, no problems at all but on the staging server, I get the following error referencing the line cotaining ->chunk(1000, function($results) use ($listId) { $this->subscribeEmails($listId, $results); });: ``` Using $this when not in object context ``` Is this a PHP version issue or am I missing something here?

Original source