Tutorials, PHP & MySQL

Using closures and $this within a class with PHP

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.

David Carr

David Carr

For the past 12 years, I’ve been developing applications for the web using mostly PHP. I do this for a living and love what I do as every day there is something new and exciting to learn.

In my spare time, the web development community is a big part of my life. Whether managing online programming groups and blogs or attending a conference, I find keeping involved helps me stay up to date. This is also my chance to give back to the community that helped me get started, a place I am proud to be apart of.

Besides programming I love spending time with friends and family and can often be found together going out catching the latest movie, staying in playing games on the sofa or planning a trip to someplace I’ve never been before.