3

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

1
  • 2
    Small tip (if this is PHP5): instead of function Manual use function __construct and instead of parent::Controller() use parent::__construct() Commented Jun 29, 2010 at 23:18

7 Answers 7

8

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

Perhaps you meant $this->myVar?

Sign up to request clarification or add additional context in comments.

1 Comment

Yup: $this-> when in an object context, self:: when in a static context.
4

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

Comments

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

Comments

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

Comments

2

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

echo $myVar;

You should do:

$this->myVar;

Comments

1

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;

Comments

1

$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

Comments

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.