0

In PHP you can do the following:

$foo = new Foo();
$foo->$newPropertyName = $value;

To dynamically add new property to the object. However when I try to do that:

$this->$newPropertyName = $value;

It doesn't work. How can I dynamically add new property from within the object?

UPDATE:

My class inherits from Yii CFormModel class. CFormModel overrides the PHP __set method so it causes the problem. How to do what I want? How to use default __set method?

3
  • 1
    $foo->newPropertyName = $value; Commented Jul 7, 2014 at 11:05
  • 1
    @user3234352 - dollar is needed as new property name comes from variable Commented Jul 7, 2014 at 11:48
  • 1
    It's not nonsense. $newPropretyName is a variable that holds the new property name. I don't want to create property newPropertyName. The property name is unknown to the developer. It is going to come from database. Commented Jul 10, 2014 at 13:54

2 Answers 2

1
$this->newPropertyName = $value;

can be called from inside any method of a class. in public scope it's that way:

$foo = new Foo();
$foo->newPropertyName = $value;

when using $this-> you don't put dollar signs.

However, you can try and force php to evaluate your variable (as in can vary) property name before assigning it to your property like this:

$foo->{$newPropertyName} = $value;
Sign up to request clarification or add additional context in comments.

Comments

0

It does work dynamically, there must be a bug in your code (maybe mispelling $newPropertyName)?

class Foo {

    public function addProperty($newPropertyName, $value) {
        $this->$newPropertyName = $value;
    }

}

$foo = new Foo();
$foo->addProperty('weather', 'raining');
echo $foo->weather;

2 Comments

Hm, I just got the "Property Foo.xxx not defined" error. My PHP v. is 5.4.16 so it shouldn't be a problem.
Ah, I guess it might be because PHP magic __set ang __get methods are overriden by base class. That makes things more complicated... The base class is yii CFormModel.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.