this keyword inside slim framework closure

118 views Asked by At

recently i started to learn API in PHP, i start to learning basic stuffs related to API then i decided to learn a framework and i choose slim microframework so i was reading the Dependency Container documentation and i saw this example

$app->get('/foo', function ($req, $res, $args) {
$myService = $this->get('myService');

return $res;

});

here this keyword refers to Container object so i want to know how it is possible to refer an object with this keyword in PHP closure?

2

There are 2 answers

0
MMD On BEST ANSWER

after couple of hours searching i got my answer so i want to share it

class A{
private $privateData = 2;

public function get($func){
    $c=Closure::bind($func,$this,"A");
    $c();
}

public function getPrivateData(){
    return $this->privateData;
 }
}


$a=new A();
$a->get(function (){
    var_dump($this->getPrivateData());
});

https://codesamplez.com/programming/php-closure-tutorial

0
cssBlaster21895 On

It seems that the $this is the $app in this context. And from the earlier part of the documentation you can see that you create the container, add it to the app. So the container is there, injected.

$container = new \Slim\Container;
$app = new \Slim\App($container);

Although Slim is a microframework - it's not easy. You use Slim 3, no problem with that. If you want to understand better how the things could be structured - I recommend this tutorial (it's for Slim 4).