johnk
johnk

Reputation: 400

How to dynamically assign a value to a class property in PHP?

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);

Upvotes: 0

Views: 1476

Answers (3)

Artefacto
Artefacto

Reputation: 97805

$obj->$propName = $value;

Upvotes: 4

Gordon
Gordon

Reputation: 316969

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

Upvotes: 2

Mike B
Mike B

Reputation: 32145

Like this?

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

Upvotes: 1

Related Questions