ageusz
(Ageusz)
July 7, 2014, 12:21pm
1
Normally I would do the following:
public function addProperty($newPropertyName, $value) {
$this->$newPropertyName = $value;
}
But my Foo class extends the CComponent so the magic __set and __get are overrided.
How can I add new property dynamically from within the Foo class?
louisgac
(Louisgac Development)
July 7, 2014, 12:25pm
2
http://www.yiiframework.com/doc/api/1.1/CComponent
A property is defined by a getter method, and/or a setter method. Properties can be accessed in the way like accessing normal object members. Reading or writing a property will cause the invocation of the corresponding getter or setter method, e.g
$a=$component->text; // equivalent to $a=$component->getText();
$component->text='abc'; // equivalent to $component->setText('abc');
The signatures of getter and setter methods are as follows,
// getter, defines a readable property 'text'
public function getText() { ... }
// setter, defines a writable property 'text' with $value to be set to the property
public function setText($value) { ... }
Also :
http://www.yiiframework.com/wiki/167/understanding-virtual-attributes-and-get-set-methods/#hh3
Many users who discover the PHP magic mathods of __get and __set will find themselves enamoured with them, and attempt to use them in their own code. This is possible, but it’s almost always a bad idea.
ageusz
(Ageusz)
July 7, 2014, 12:41pm
3
I aw aware of "black" magic of the __set and __get methods but thanks for notice.
The solution with setProperty() and getProperty() methods won’t allow me to do it dynamically right? I have to define those methods in class so there’s no dynamic. The problem is my FooForm class will have few attributes that I’m not aware of at the class creation time. That’s why I need to dynamically add the properties.
louisgac
(Louisgac Development)
July 7, 2014, 1:16pm
4
Well, I’m not sure of you’re trying to do, but you’re trying to do something like :
$foo->bar = "fooBar";
even if $bar is not defined in Foo, or if there is no method getBar() in Foo.
Well, your trying to implement some registry pattern right ?
Have a look here :
http://www.yiiframework.com/forum/index.php/topic/3506-yii-registry/
— EDIT —
Still not sure, but in first link I provide you :
http://www.yiiframework.com/wiki/167/understanding-virtual-attributes-and-get-set-methods/