Fatal error: Using $this when not in object context in PHP

Whenever you got this error check the following:

1. Make sure the $this-> is used inside the object and referring to the class’s and inherited non-static members.

2. Make sure the called members of the object are properly addressed as static or member/function variables

Do you know the different different post types?

Here is an example for the second one.

Assume you have the following object


class Example
{
   function getExampleText()
   {
      return "Example Text";
   }
   static function getStaticExampleText()
   {
      return "Static Example Text";
   }
}

While accessing, if the code tries something like this one,

$example = new Example();
Example::getExampleText(); //Trying to access non-static as static

Then you would have the error

Can’t use method return value in write context – php Error

Yup, just to share – as usual.
While working on one of my projects I run this error. Here is the snippet where the error occurs:

....
        $carPrice = $this->getCarPrice(); // this would return object of CarPrice
        if (empty($carPrice->getCarPriceId()))
        {.....

Where $carPrice is an object to be returned after passing an array of data ($new_price) to the controller.
And on the next line, I was trying to if priceId of the car is not empty.
The problem is caused on the second operand of the if statement (empty($carPrice->getCarPriceId()) –
Here is how I get fool around..

...
$car_price_id = $carPrice->getCarPriceId();
if (empty($car_price_id))
{
...

It happens that function empty() [and even isset() ] do expect a variable to be checked otherwise, parse error will happen.