简体   繁体   中英

PHP Closures - How do I call a class function with $this

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM