Dynamic Class Attributes


(Notulei) #1

Hi,

Is there a reason why in yii I can not create dynamic class atributes.

This is what I get when instantiating A:

Property "A.dynamic" is not defined

Thanks and sorry, but I could’t find an answer in the forums.




class A extends CModel

{

    public $var1;


    public function __construct()

    {

        $this->dynamic= 'test';

    }

}





(Jaymard Colmenar) #2

Hi yiisus,

You should declare $dynamic in the class.




class A extends CModel {

    public $var1;

    public $dynamic; //Declare dynamic as a class variable


    public function __construct()

    {

        $this->dynamic= 'test';

    }

}




(Ben) #3

The answer to your question can be found in the __set() magic method that is part of CComponent, which means all component subclasses are subject to this method of setting. The code does not allow for dynamic variables; as you can see, it throws an exception. For more information about the reasoning behind the method, read the CComponent documentation.


(Notulei) #4

Thanks Jaymard. I just realized that I provided a bad example. But thanks to "Yoda Pop" and Calvaria in the other thread that you replied, I learned that I need to use magic functions (__set() & __get) to accomplish what I needed.

Thanks Master Yoda Pop :)

I definitely will go over the CComponent documentation. I have so many questions …, but I’m moving on with my project.