【问题标题】:Using $this when not in object context - in Laravel controller不在对象上下文中使用 $this - 在 Laravel 控制器中
【发布时间】:2012-12-18 17:32:20
【问题描述】:

我正在使用 Laravel,我刚刚将在本地运行的代码移动到 Live 中,并且在我的“用户”控制器中出现以下异常:

Unhandled Exception
Message:
Using $this when not in object context

奇怪的是,这是一个类并且在本地工作得很好,所以我不希望解决方案使用静态符号。只有当我将其推广到 Live 时,我才会收到此错误。会不会是 Laravel 核心中的某些东西在 Live 中没有正确加载控制器类?

有没有人在将他们的代码推广到 Live 后遇到过这种情况?有什么想法吗?

更新:发生错误的代码的 sn-p。请记住此代码在本地工作,因此我认为缺少某些内容,而不是需要更改此代码以解决此问题。

class User_Controller extends Base_Controller {

...

public function action_register() {
   ...
    if ($user) {
        //Create the Contact
        DB::transaction(function() use ($user_id) {
            $org = $this->create_org($user_id); //failing on this line with exception. btw $user is created fine
            $this->create_contact($org->id);
            $this->create_address($org->id);
    });

    private function create_org($user_id) {
        $result = Org_type::where('name','=',$_POST['org_type'])->first();

        $org = Org::Create(
            array(
                'name' => $_POST['org_name'],
                'user_id' => $user_id,
                'org_type_id' => $result->id,
            )
        );
        return $org;
    }

...

【问题讨论】:

  • 你能发布堆栈跟踪和/或完整的函数/类代码吗?希望它可以帮助我们查明问题:)
  • 我也刚刚注意到 - 这是在静态函数中吗? $this 在静态函数中不起作用。
  • 感谢 Daniel,刚刚更新了代码 sn-p。没有对 $this 的引用带有一个非静态的控制器功能。它在我的笔记本电脑上本地运行良好:-0
  • 添加了我的答案,试一试,希望可以解决您的问题:)

标签: php object controller laravel unhandled-exception


【解决方案1】:

问题似乎是您在提供给DB::transaction 函数的闭包内使用$this,我不确定它为什么会在live 本地工作,但必须将控制器的实例导入到函数中才能使用。

为了避免混淆,最好的方法是给它起别名,并可能通过引用传递它,这样你就不会复制它,比如:

$this_var = $this;
DB::transaction(function() use ($user_id, &$this_var as $controller) {
        $org = $this->create_org($user_id); //failing on this line with exception. btw $user is created fine
        $controller->create_contact($org->id);
        $controller->create_address($org->id);
});

我不完全确定语法是否完美,但逻辑是合理的。

【讨论】:

  • 感谢 Daniel,尽管它没有解释为什么它在本地工作,而不是当我将代码发送到 Live 时?我在想 Live 中缺少一些东西,但不确定是什么?根据您的回答,它不应该在本地也失败吗?!
  • 应该,是的。但是如果你在本地运行 PHP5.4,它们似乎支持$this,如果你的主机运行的是 PHP5.3,那就可以解释差异了。
  • 请参阅stackoverflow.com/questions/5734011/… 的答案以获取示例。
  • 顺便说一句,刚刚尝试了您的建议并收到以下错误:未处理的异常消息:无法使用 $this 作为词法变量
  • @user1746582 啊,好的,我已经编辑了解决方案来解决这个问题,希望如此。
猜你喜欢
  • 2017-04-17
  • 2013-12-14
  • 1970-01-01
  • 2023-03-22
  • 2022-12-03
  • 1970-01-01
  • 1970-01-01
  • 2015-06-25
  • 2015-02-12
相关资源
最近更新 更多