PHP: variable scope in OOP?

Here is my code:

class Manual extends controller {

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


    }

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

}

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

thank

+3
source share
7 answers

In your code $myVaris local to each method.

Did you mean $this->myVar?

+8
source

You need to use $ this 'pointer'.

eg:.

class Test
{
     protected $var;

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

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

   private $myVar;

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

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

OOP- 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;
   }
+4
function doStuff(){
    echo $this->myVar; 
}
+2

$myVar , :

echo $myVar;

:

$this->myVar;
+2

, $myVar .

$myVar

protected $myVar;

$this ,

$this->myVar;
+1

$myVarmust be declared as public/protectedin the parent class or declared in the descedent class, and in your method doStuff()you should write $this->myVarnot$myVar

+1
source

Source: https://habr.com/ru/post/1752311/


All Articles