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();
Leo Houer
  • 347
  • 2
  • 4
  • 8

1 Answers1

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.

George Brighton
  • 5,131
  • 9
  • 27
  • 36
  • "because you've called a non-static method statically" - activate() is defined as STATIC ??? – Leo Houer Oct 09 '13 at 01:12
  • You're calling `redis_query()` statically using `self`. – George Brighton Oct 09 '13 at 01:15
  • Indeed calling a static method despite having instantiated the object using new will execute your code in the static context leading to your error. – EmmanuelG Oct 09 '13 at 01:15
  • 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! – Leo Houer Oct 09 '13 at 02:32