dynamic class property $$value in php

Viewed 34150

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?

6 Answers

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

echo $this->$string;

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

However, this

$this->$$string;

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

$foo = 'bar';
$bar = 'foobar';
echo $$foo; //-> $'bar' -> 'foobar'

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

public function foobar($string)
{
     echo $this->$string; //will work
}
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 $.

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.

Related