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);
$obj->$propName = $value;
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
Like this?
$myClass = new stdClass();
$myProp = 'foo';
$myClass->$myProp = 'bar';
echo $myClass->foo; // bar
echo $myClass->$myProp; // bar
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.