在不在对象上下文中时使用$This访问不起作用的路由中的$This(&q;) [英] Access $this inside a route in doesn't work "Using $this when not in object context"

查看:44
本文介绍了在不在对象上下文中时使用$This访问不起作用的路由中的$This(&q;)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在路由的函数中使用$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 SlimApp();

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

$app->run();

我已尝试基于this实现它。

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

推荐答案

使用字符串声明函数时,不能在函数内部使用$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

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

这篇关于在不在对象上下文中时使用$This访问不起作用的路由中的$This(&q;)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆