0

To set an attribute val I would use:

$product->setNameofmyattribute('somestuff');

Now I have the name of my attribute in a string.

So how can I merge:

$attribute = 'Nameofmyattribute';
$product->set[here comes my string]('somestuff');

2 Answers 2

4

You can use setDataUsingMethod() defined in Varien_Object.
For example, if your attribute is called some_attribute the following are identical:

$product->setSomeAttribute('some_value');  
$product->setDataUsingMethod('some_attribute', 'some_value');

[Edit: and a bit off topic]
It works the same way for getters:

$product->getSomeAttribute();

is the same as

$product->getDataUsingMethod('some_attribute');
3
  • That's a really creative means of handling it.
    – philwinkle
    Jul 8, 2013 at 14:02
  • Thanks, this works great. And no, it's not off topic but very helpful! :-) Jul 8, 2013 at 14:54
  • Great help! If one uses the setDataUsingMethod method ... how then can we save the value? do we issue saveAttribute or need to product->save (rather not the last) ..... help appreciated
    – snh_nl
    Jun 26, 2017 at 7:46
1

PHP can interpret this automatically, but you'll have to prepend the set keyword:

$attribute = 'Nameofmyattribute';
$setter = 'set' . $attribute;
$product->$setter('somestuff');

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.