5

I created a public static function in a controller and I need to access a class property which is set on the constructor. I normally use $this->something to access such class properties, but this time, I got this error:

Using $this when not in object context

Here's the code:

public static function PayExecute() {
    $paymentId = Input::get('paymentId');
    $PayerID = Input::get('PayerID');

    $cont = $this->apiContext;
}
1
  • 3
    you cannot use $this on static functions Commented Dec 2, 2016 at 10:14

6 Answers 6

18

You need $apiContext be declared as static property, and you need use static of self keyword. Something like this:

class YourController extends BaseController
{
    private static $apiContext = '';

    public static function PayExecute()
    {
        $paymentId = Input::get('paymentId');
        $PayerID = Input::get('PayerID');

        $cont = static::$apiContext;
    }
}

BTW: Be aware about fact that static is late static binding.

Sign up to request clarification or add additional context in comments.

Comments

8

You cannot use "$this" in static methods. You do have access to "self::" though, but remember that you cannot access methods / properties that require the current class to be instanciated.

Comments

3

The source of this problem is the wrong instantiation of the Excel class.

Check your controller.

Wrong: use Maatwebsite\Excel\Excel;

Correct: use Maatwebsite\Excel\Facades\Excel;

Comments

1

In my case, I had a non-static controller function (so public function myFunc instead of public static myFunc), but I forgot a line where I was calling the function statically (like MyController::myFunc).

Removing this line fixed the error.

Moral of the story: when your function uses $this->something, do not call the function statically :)

Comments

1

kindly use self:: instead of $this-> if you are calling to the function which refers to the same function

public static function PayExecute() {
   $paymentId = Input::get('paymentId');
   $PayerID = Input::get('PayerID');

   $cont = self::apiContext;
}

Comments

0

you have to create new instance and then can access its property

public static function PayExecute() {
    $paymentId = Input::get('paymentId');
    $PayerID = Input::get('PayerID');

    $cont = (new static)->apiContext;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.