Industrial
Industrial

Reputation: 42758

PHP: Variable scope in OOP?

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

Upvotes: 3

Views: 1556

Answers (7)

Ris90
Ris90

Reputation: 841

$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

Upvotes: 1

DrColossos
DrColossos

Reputation: 12988

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;
   }

Upvotes: 4

Alana Storm
Alana Storm

Reputation: 166046

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;

Upvotes: 1

Sarfraz
Sarfraz

Reputation: 382656

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

echo $myVar;

You should do:

$this->myVar;

Upvotes: 2

VDVLeon
VDVLeon

Reputation: 1394

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;
     }
};

Upvotes: 4

Luis Melgratti
Luis Melgratti

Reputation: 12050

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

Upvotes: 2

timdev
timdev

Reputation: 62884

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

Perhaps you meant $this->myVar?

Upvotes: 8

Related Questions