2

我收到一个错误,例如Fatal error: Using $this when not in object context in ..\controllers\ServiceRequestController.php on line 661使用 EasyTabs 扩展中的控制器操作调用视图文件时。我在视图文件和控制器
中调用这样的控制器操作
ServiceRequestController::actionTest();

     public static function actionTest()  
   {
        $this->redirect('test');
    }

我怎样才能摆脱这个错误?当我用谷歌搜索时,我发现$this cannot be used in a static method.. 所以我尝试
$model = new ServiceRequest(); $model->Test();在我的视图文件中使用。但它显示错误,因为ServiceRequest and its behaviors do not have a method or closure named "actionTest". 有人可以帮我修复错误吗?在此先感谢我尝试使用此链接进行修复。但我认为我错了。PHP 致命错误:不在对象上下文中使用 $this

4

4 回答 4

9

static定义操作时不要使用关键字。

您可以在此处阅读有关静态方法和属性的更多信息:

http://de1.php.net/manual/en/language.oop5.static.php

于 2013-05-02T07:40:50.827 回答
2

尝试这个

   self::actionTest();

反而

   ServiceRequestController::actionTest();
于 2013-12-29T18:24:42.820 回答
0

当使用 $this 关键字时,对象需要在某个时候被实例化。如果你有一堂课:

class Example {

    private $word = 'hello';

    public static function hello() {
        echo 'I can be called by writing:';
        echo 'Example::yo()';
    }

    public function world() {
        echo 'If this class has been instantiated, ( new Example; )';
        echo '$this->word will be hello';
        echo 'If this class hasn't been instantiated, you will get your error';
    }
}

一个类的特定实例可以从它内部的方法中被称为 $this。

你可以写:

$example1 = new Example;
$example2 = new Example;
$example3 = new Example;

在 $example1 内部,$this 将引用与 $example1 从外部引用的相同内容。所以你可以像这样改变 $example1 的 $word:

$example1->word = 'yo';    // from outside of the class
$this->word = 'yo';        // from inside of the class

但是,在使用 new 关键字实例化类之前,还没有 $this 存在。该类是一个蓝图,您可以使用 new 关键字从中创建对象,然后可以在内部将其称为 $this。

于 2013-05-02T06:08:51.237 回答
0

我通过更正我的 URL 为 yii2 修复了这个错误,例如

 http://localhost/e-compare2/backend/web/index.php?r=crud/make
于 2014-12-02T11:56:30.773 回答