Wednesday, September 29, 2010

Fatal error: Using $this when not in object context

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

This has mostly two different reasons.

1. $this is used outside of a class.

class test{

   var $runtest;

   function test(){
      $this->runtest = 1; // proper usage
   }

   function printThis(){
      echo $this->runtest;
   }
}

$object = new test();
echo $this->runtest; // fails this not part of an object.
echo $object->runtest; // success 

2. The class method contains $this but was called in a static way.

class TestClass { 
    var $test; 

    function testMethod() { 
        $this->test = 'test'; 
    } 
} 

TestClass::testMethod(); // Error 

If the class needs to be used static the other variable or method needs to be called static as well.

class TestClass { 
    var $test; 

    function testMethod() { 
        TestClass::$test = 'test'; 
    } 
} 

0 comments:

Post a Comment