views:

122

answers:

7

Hi everybody,

Here's my code:

class Manual extends controller {

    function Manual(){
        parent::Controller();
     $myVar = 'blablabla';


    }

    function doStuff(){
        echo $myVar; // Doesn't work.
    }

}

I've tried various methods to make it work, but I've can't get my head around it. What can I do?

Thanks

+8  A: 

In your code, $myVar is local to each method.

Perhaps you meant $this->myVar?

timdev
Yup: `$this->` when in an object context, `self::` when in a static context.
Pekka
+2  A: 
function doStuff(){
    echo $this->myVar; 
}
Luis Melgratti
+4  A: 

You need to use the $this 'pointer'.

e.g.:

class Test
{
     protected $var;

     public function __construct()
     {
          $this->var = 'foobar';
     }

     public function getVar()
     {
          return $this->var;
     }
};
VDVLeon
+4  A: 
class Manual extends controller {

   private $myVar;

    function Manual(){
        parent::Controller();
        $this->$myVar = 'blablabla';
     }

    function doStuff(){
        echo $this->$myVar; 
    }
}

Even more OOP-like with Setters/Getters

class Manual extends controller {

   private $myVar;

    function Manual(){
        parent::Controller();
        setMyVar('blablabla');
    }

    function doStuff(){
        echo getMyVar();
    }

    function getMyVar() {
        return $this->myVar;
    }

   function setMyVar($var) {
       $this->myVar = $var;
   }
DrColossos
+2  A: 

The variable $myVar should be property of a class, and you can not do:

echo $myVar;

You should do:

$this->myVar;
Sarfraz
+1  A: 

As written, $myVar is local to both methods.

You need to declare $myVar as a property in the class body

protected $myVar;

and then use the pseudo variable $this to access the property in methods, including the constructor

$this->myVar;
Alan Storm
+1  A: 

$myVar field must be declarated as public/protected in the parent class or declarated in the descedent class, and in yours doStuff() method you must write $this->myVar not the $myVar

Ris90