Using $this when not in object context in Yii

12.7k Views Asked by At

Iam getting an error like Fatal error: Using $this when not in object context in ..\controllers\ServiceRequestController.php on line 661 when calling a view file using controller action from EasyTabs extension.
Iam calling the controller action like this in the view file
ServiceRequestController::actionTest();
and in controller

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

How can I get rid of this error?? When I googled, I found that $this cannot be used in a static method. . So I tried out using
$model = new ServiceRequest(); $model->Test(); in my view file.But it shows the error as ServiceRequest and its behaviors do not have a method or closure named "actionTest". Can anyone help me fixing the error? Thanks in advance I tried to fix using this link . But I think Iam mistaken. PHP Fatal error: Using $this when not in object context

4

There are 4 best solutions below

0
On

try this

   self::actionTest();

instead

   ServiceRequestController::actionTest();
0
On

I fixed this error for yii2 by correcting my URL e.g.

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

Do not use the keyword static when you define the action.

You can read more about static methods and properties here:

https://www.php.net/manual/en/language.oop5.static.php

1
On

When using the $this keyword the object needs to have been instantiated at some point. If you've got a class:

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

A particular instance of a class can be referred to as $this from methods that are inside of it.

You could write:

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

Inside of $example1, $this would refer to the same thing that $example1 refers to from outside of it. So you could change $example1's $word like so:

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

Before you're instantiated the class with the new keyword though, there is no $this in existence yet. The class is a blueprint, and you create objects out of it using the new keyword which can then be referred to from within as $this.