-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

1

2 Answers 2

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();
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();
2
  • Right, that was a typo.
    – brian
    Commented Oct 2, 2014 at 6:04
  • After I change it, i get the following error Access to undeclared static property: foo::$_var on line 4. Commented Oct 2, 2014 at 6:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.