如何动态地为PHP中的类属性赋值?

时间:2010-06-11 11:38:33

标签: php reflection properties variable-assignment dynamic

我想动态地在类属性中赋值(即使用变量引用它)。

#Something like: 
setPropValue($obj, $propName, $value);

3 个答案:

答案 0 :(得分:4)

$obj->$propName = $value;

答案 1 :(得分:2)

如果你想为static members执行此操作,可以使用变量:

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

答案 2 :(得分:1)

喜欢这个吗?

$myClass = new stdClass();
$myProp = 'foo';
$myClass->$myProp = 'bar';
echo $myClass->foo; // bar
echo $myClass->$myProp; // bar