1

I'm having a little trouble with PHP Closures.

Okay, so let's say I have:

$router->bind('~/~', function()
{
    print "I'm on the home page";
});

$shel = new Shel($config, $router);
$shel->start();

Now, all my functions are called by Shel. Inside Shel, there's a function load(). Is there a way to call Shel::load() from the closure that I've binded, using $this?

Cheers!

chintanparikh
  • 1,632
  • 6
  • 22
  • 36
  • 1
    possible duplicate of [PHP 5.4 - 'closure $this support'](http://stackoverflow.com/questions/5734011/php-5-4-closure-this-support) – Gordon Mar 23 '12 at 13:35
  • 1
    I'm on 5.3.8. Gordon, I read through that thread, but I think my issue is a little different, I should have specified in the original post, it's now been updated. – chintanparikh Mar 23 '12 at 13:37

1 Answers1

4

PHP 5.3: https://wiki.php.net/rfc/closures/object-extension

For PHP 5.3 $this support for Closures was removed because no consensus could be reached how to implement it in a sane fashion. This RFC describes the possible roads that can be taken to implement it in the next PHP version.

So in PHP 5.3 you had to workaround a bit:

$that = $this;
$router->bind('~/~', function() use ($that)
{
    print "I'm on the home page";
});

For 5.4 you can use just $this.

dan-lee
  • 14,365
  • 5
  • 52
  • 77
  • I'm on 5.3.8. However, I'm still not entirely sure how that would help? I just realised I forgot to mention one important aspect of the problem, I'll update the post. – chintanparikh Mar 23 '12 at 13:36
  • 1
    I see, in that case, you'd have to bind *after* you set your $router object into Shel, then you could just use($shel) and call it with $shel->load(). Other way around it's not possible, because the scope is not know to the anonymous function. – dan-lee Mar 23 '12 at 13:45
  • Hm, I see. In that case, should I make my Router class static? That's the easiest way I can see to do it. – chintanparikh Mar 23 '12 at 13:56
  • Well yes you'd need to make `load()` static. The class itself cannot be static in PHP. – dan-lee Mar 23 '12 at 13:58
  • Ugh, this is what happens when I take a break from PHP. Haha cheers! – chintanparikh Mar 23 '12 at 14:17