开发者

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 开发者_StackOverflow中文版to make it work, but I've can't get my head around it. What can I do?

Thanks


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

Perhaps you meant $this->myVar?


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


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


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


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

echo $myVar;

You should do:

$this->myVar;


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;


$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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜