-1
class A {
    protected $bar = 'bar';
    public function foo() {
        echo $this->$bar;
    }
}

$a = new A();
$a->foo();

It's boggling my mind that this isn't working. I come from C++ and C# so it's likely something I don't understand about PHP.

Nick Strupat
  • 4,928
  • 4
  • 44
  • 56

3 Answers3

6

Why does this simple code yield 'Undefined variable: bar'

Because PHP tries to evaluate the variable $bar before evaluating $this->. Since there is not a $bar variable, it yields a notice.

Remove the $ in front of $bar:

echo $this->bar;

I would encourage you to read the Variable Variables section of the docs as well as OOP Basics.

Jason McCreary
  • 71,546
  • 23
  • 135
  • 174
  • I'm curious, why does dynamic language imply that specific order of evaluation? – Nick Strupat Nov 15 '13 at 14:41
  • 1
    It does not imply specific order of evaluation, more the variable variables. I mentioned it since you noted coming from C++. Which is far more static than PHP. Nonetheless, I have adjusted my answer. – Jason McCreary Nov 15 '13 at 14:44
2

When you access a member, you only need the dollar-sign before this; i.e. access it like this instead:

echo $this->bar;
Peter Bloomfield
  • 5,578
  • 26
  • 37
0

try this

public function(){
  echo $this->bar;
}

When use the $this then couln't use the symbol $ before variable $this->$variable but $this->variable;

A. Zalonis
  • 1,599
  • 6
  • 26
  • 41