4

I have looked for other questions covering this error, but could not find a case that applies to my problem.

Basically the static method in my class invokes a non-static method which in return invokes another non-static method.

This throws an Fatal error:

Fatal error: Using $this when not in object context in class.php on line ...

I can't figure out why it is not okay to call a non-static class method from another non-static class method via $this. Is it because they are both invoked from a static function and hence there is no $this instance ?

Here is the (simplified) class:

class Redis_Provision {

    public $redis = NULL;

    public function redis_query()
    {
        if(is_null($this->redis)) {
            $this->setBackend();   <------- This throws the fatal error
        }
        return $this->redis;
    }

    public function setBackend()
    {
        $this->redis = new Redis();
        $this->redis->connect();
    }

    public static function activate()
    {

        if( self::redis_query()->ping())
        {
            // Do stuff
        }
    }
}

Which i would invoke via:

$redis_provision = new Redis_Provision();
$redis_provision->activate();
0

1 Answer 1

3

The error occurs because you've called a non-static method statically (this will have risen an E_STRICT - check your error reporting), which doesn't stop execution but means there's no object context ($this cannot be used).

The proper way to fix the error is to instantiate the class in activate(), and call the redis_query() method on the object, e.g.

$redis_provision = new Redis_Provision();
if($redis_provision->redis_query()->ping()) { ... }

This means that redis_query() executes with a context, and so functions normally.

Also, the activate() method is static, so you don't need to create a new object in your invocation code. You can just call Redis_Provision::activate() directly.

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

4 Comments

"because you've called a non-static method statically" - activate() is defined as STATIC ???
You're calling redis_query() statically using self.
Indeed calling a static method despite having instantiated the object using new will execute your code in the static context leading to your error.
I called redis_query() statically, because i thought i am not allowed to call it via $this->method from a static method. Nevertheless you brought me on the right track, George. I am now initiating the class from a new static method which is invoked via Redis_Provision::getInstance(). Then i call activate() from within the __construct() method. I think you call it a singleton class. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.