0

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

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

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

有没有人在将他们的代码推广到 Live 后经历过这种情况?有任何想法吗?

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

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;
    }

...

4

1 回答 1

3

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

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

$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);
});

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

于 2013-01-04T09:54:30.410 回答