【问题标题】:Using $this when not in object context in Yii在 Yii 中不在对象上下文中时使用 $this
【发布时间】:2013-05-02 05:32:44
【问题描述】:

使用 EasyTabs 扩展中的控制器操作调用视图文件时,我收到类似 Fatal error: Using $this when not in object context in ..\controllers\ServiceRequestController.php on line 661 的错误。
我在视图文件中调用这样的控制器操作
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 Fatal error: Using $this when not in object context

【问题讨论】:

    标签: php yii yii-extensions yii-components yii-events


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      试试这个

         self::actionTest();
      

      改为

         ServiceRequestController::actionTest();
      

      【讨论】:

        【解决方案3】:

        当使用 $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。

        【讨论】:

        • 在这种情况下如何实现?
        【解决方案4】:

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

         http://localhost/e-compare2/backend/web/index.php?r=crud/make
        

        【讨论】:

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