$this 包含在这个 SLIM 代码中的哪个对象引用?
Which object reference does $this contain in this SLIM code?
我正在尝试使用 SLIM 的树枝视图渲染一个简单的 HTML 视图。我想知道当我使用 get() 函数进行路由时
//Get container
$container = $app->getContainer();
//Register Component on container
$container['view'] = function($container) {
$view = new \Slim\Views\Twig('templates', [
'cache' => false
]);
$view->addExtension(new \Slim\Views\TwigExtension(
$container['router'],
$container['request']->getUri()
));
return $view;
};
$app->get('/', function(Request $request, Response $response) {
return $this->view->render($response, 'index.html');
});
$app->run();
那么$this包含了哪个对象引用。
请帮我澄清一下。谢谢
$this
是slim的依赖注入容器:Slim\Container
在闭包的 DeferredCallable
, you can see that slim uses the bindTo
函数中设置 $this
实例。
$this
指向创建闭包的class
class a {
public function test(){
//closure is defined in the class
return function(){
print_r($this);//so you have access to $this
};
}
}
$a = new a();
$a->test();
在您的示例中,您使用的是 https://www.slimframework.com/ 并且它不是以这种方式工作的。但它基本上适用于 php.
来自 SlimFramework docs :
Note inside the group closure, $this
is used instead of $app
. Slim
binds the closure to the application instance for you, just like it is
the case with route callback binds with container instance.
- inside group closure,
$this
is bound to the instance of Slim\App
- inside route closure,
$this
is bound to the instance of Slim\Container
我正在尝试使用 SLIM 的树枝视图渲染一个简单的 HTML 视图。我想知道当我使用 get() 函数进行路由时
//Get container
$container = $app->getContainer();
//Register Component on container
$container['view'] = function($container) {
$view = new \Slim\Views\Twig('templates', [
'cache' => false
]);
$view->addExtension(new \Slim\Views\TwigExtension(
$container['router'],
$container['request']->getUri()
));
return $view;
};
$app->get('/', function(Request $request, Response $response) {
return $this->view->render($response, 'index.html');
});
$app->run();
那么$this包含了哪个对象引用。 请帮我澄清一下。谢谢
$this
是slim的依赖注入容器:Slim\Container
在闭包的 DeferredCallable
, you can see that slim uses the bindTo
函数中设置 $this
实例。
$this
指向创建闭包的class
class a {
public function test(){
//closure is defined in the class
return function(){
print_r($this);//so you have access to $this
};
}
}
$a = new a();
$a->test();
在您的示例中,您使用的是 https://www.slimframework.com/ 并且它不是以这种方式工作的。但它基本上适用于 php.
来自 SlimFramework docs :
Note inside the group closure,
$this
is used instead of$app
. Slim binds the closure to the application instance for you, just like it is the case with route callback binds with container instance.
- inside group closure,
$this
is bound to the instance ofSlim\App
- inside route closure,
$this
is bound to the instance ofSlim\Container