0

I would like to assign a value in a class property dynamically (that is referring to it using a variable).

#Something like: 
setPropValue($obj, $propName, $value);
Joe Mastey
  • 26,514
  • 12
  • 79
  • 104
johnk
  • 380
  • 1
  • 4
  • 14
  • Dup of [Can you create instance properties dynamically in PHP?](http://stackoverflow.com/q/829823/) – outis Jul 11 '12 at 22:08

3 Answers3

4
$obj->$propName = $value;
Artefacto
  • 93,596
  • 16
  • 191
  • 218
2

In case you want to do this for static members, you can use variable variables:

class Foo
{
    public static $foo = 'bar';
}

// regular way to get the public static class member
echo Foo::$foo; // bar

// assigning member name to variable
$varvar = 'foo';
// calling it as a variable variable
echo Foo::$$varvar; // bar

// same for changing it
Foo::$$varvar = 'foo';
echo Foo::$$varvar; // foo
Gordon
  • 305,248
  • 71
  • 524
  • 547
1

Like this?

$myClass = new stdClass();
$myProp = 'foo';
$myClass->$myProp = 'bar';
echo $myClass->foo; // bar
echo $myClass->$myProp; // bar
Mike B
  • 31,390
  • 13
  • 83
  • 110