Using closures and $this within a class with PHP

David Carr

Tutorials PHP & MySQL

Closures are really useful, especially for creating plugins when a full blown controller is not needed, today I came across a problem when using a closure within a class and trying to use $this-> which resulted in getting this error:

Using $this when not in object context.

The problem is PHP 5.3 does not let you use $this inside a closure, take this example I have a method with a controller inside I'm trying to use $this-> to refer to a object. 
 

public function routes(){

    Router::any('(:all)', function($request) {
        $row = $this->_db->get_post_by_slug($request);
    }

}


This will result in an error when using PHP 5.3 or less for 5.4+ it works fine. So if you're still using 5.3 WHY? best to upgrade to latest stable release.

To make this backwards compatible and work in 5.3 a variable can hold a reference to $this and that can be passed/bound to the closures.
To do this create a variable and pass it $this<

$class = $this;

Then for the closures use the use function and pass in $class with a & to it's not passing it as a reference but referring to the actual object.
 

Router::any('(:all)', function($request) use (&$class){

The important part is use (&$class) that makes $class available to the closure which is the same as $this, now instead of writing $this->_db I would write $class->_db like this:

Router::any('(:all)', function($request) use (&$class){
    $row = $class->_db->get_post_by_slug($request);
}

This enables closures to refer to objects in the main class in 5.3 for 5.4+ no change is needed and $this can be used freely.

Read articles directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Copyright © 2006 - 2024 DC Blog - All rights reserved.