【问题标题】:Access $this inside a route in doesn't work "Using $this when not in object context"在路由中访问 $this 不起作用“不在对象上下文中使用 $this”
【发布时间】:2017-08-23 18:59:11
【问题描述】:

我试图在路由函数中使用$this,当我这样做时,它给了我以下错误:

Using $this when not in object context

代码如下:

function api($request, $response) {
    $response->write('REST API v1');
    $this->logger->addInfo("Something interesting happened"); 
    return $response;
}

$app = new \Slim\App();

/** my routes here **/
$app->get('/', 'api');

$app->run();

我已经尝试基于this来实现它。

为什么在函数内部使用$this 不起作用,我如何在函数内部使用$this

【问题讨论】:

  • 你在哪里使用$this->..
  • 在我所有的路由函数中
  • 为您的问题添加示例
  • @jmattheis OP 更新了示例路线

标签: php slim slim-3


【解决方案1】:

用字符串声明函数时,不能在函数内部使用$this。改用匿名函数(控制器类也可以解决):

$app->get('/', function ($request, $response) {
    $response->write('REST API v1');
    $this->logger->addInfo("Something interesting happened"); 
    return $response;
});

见:http://www.slimframework.com/docs/objects/router.html

如果你使用闭包实例作为路由回调,闭包的状态将绑定到容器实例。这意味着您将可以通过 $this 关键字访问闭包内的 DI 容器实例。

【讨论】:

    猜你喜欢
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 2012-01-02
    • 2015-06-25
    • 2013-12-14
    • 2015-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多