-1

I'm reading this tutorial about PHP Classes. I haven really fully understand it, can anyone help me out here? I came across this class

  <?php
      class foo{
         private $_var;
         static function bar(){
             return $this->_var;
         }
         function setVar($value = null){
             $this->_var = $value;
         }
      }
?>  

It says there's something wrong with the class. Is it that obvious? I dont know what's wrong with it... is it the underscore before the var? Edit: if I run this code

 $x = new foo();
 $x->setVar(1);
 echo $x->bar();

I get this message Fatal error: Using $this when not in object context in main.php on line 6 PHP Fatal error: Using $this when not in object context in main.php on line 6

  • Try to use search first: http://stackoverflow.com/questions/2350937/php-fatal-error-using-this-when-not-in-object-context – u_mulder Oct 02 '14 at 06:02

2 Answers2

0

Basically, when you use static context, you have to use self instead of $this. So, in this case, you'd have to change

return $this->_var;

with

return self::$_var;

UPDATE:

Either do this:

// traditional object context
class foo {
   private $_var;

   function bar(){
       return $this->_var;
   }

   function setVar($value = null){
       $this->_var = $value;
   }
}

$x = new foo();
$x->setVar(1);
echo $x->bar();

or do

// static context
class foo {
   static $_var;

   static function bar(){
       return self::$_var;
   }

   static function setVar($value = null){
       self::$_var = $value;
   }
}

foo::setVar(1);
echo foo::bar();
brian
  • 2,745
  • 2
  • 17
  • 33
0

Static function is called by class name or self(in the called function is in same class), you cannot call it on $this

 echo $x->bar(); // this is wrong

it should be

 echo foo::bar();
Garima
  • 174
  • 6