Search code examples
phplaravelobjectpropertiesstatic

Using $this when not in object context in a Laravel controller


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

Solution

  • 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.