views:

1371

answers:

6

How can i reference a class property knowing only a string?

class Foo
{
    public $bar;

    public function TestFoobar()
    {
        $this->foobar('bar');
    }

    public function foobar($string)
    {
         echo $this->$$string; //doesn't work
    }
}

what is the correct way to eval the string?

+9  A: 

You only need to use one $ when referencing an object's member variable using a string variable.

echo $this->$string;
Antonio Haley
+1  A: 

you were very close. you just added 1 extra $ sign.

public function foobar($string)
{
     echo $this->$string; //will work
}
Mike Stanford
A: 
echo $this->$string; //should work

You only need $$string when accessing a local variable having only its name stored in a string. Since normally in a class you access it like $obj->property, you only need to add one $.

Marc W
+2  A: 

As the others have mentioned, $this->$string should do the trick.

this->$$string;

will actually evaluate string, and evaluate again the result of that.

$foo = 'bar';
$bar = 'foobar';
echo $$foo; //-> $'bar' -> 'foobar'
Matthew H.
A: 

To remember the exact syntax, take in mind that you use a $ more than you normally use. As you use $object->property to access an object property, then the dynamic access is done with $object->$property_name.

A: 

If you want to use a property value for obtaining the name of a property, you need to use "{" brackets:

$this->{$this->myvar} = $value;

Even if they're objects, they work:

$this->{$this->myobjname}->somemethod();

Rick