![]() |
Can I add $data in constructor? - Printable Version +- CodeIgniter Forums (https://forum.codeigniter.com) +-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20) +--- Forum: Archived General Discussion (https://forum.codeigniter.com/forumdisplay.php?fid=21) +--- Thread: Can I add $data in constructor? (/showthread.php?tid=25937) |
Can I add $data in constructor? - El Forum - 12-31-2009 [eluser]shinokada[/eluser] I have the following $data in all the functions. I tried to add the following in constructor, in order to avoid repeating. But it does not work. Can I add $data in the constructor? I am repeating this. Code: $mostsold = $this->MProducts ->getMostSoldProducts(); I tried this, but it does not work. Code: function __construct(){ Can I add $data in constructor? - El Forum - 12-31-2009 [eluser]2think[/eluser] shinokada, Have you thought about extending the Controller class and just adding it there? http://ellislab.com/codeigniter/user-guide/general/core_classes.html Can I add $data in constructor? - El Forum - 01-01-2010 [eluser]Aken[/eluser] You need to define those as a class variable. The way you have it now, $data only exists in the constructor function. Use: Code: class Example extends Controller { Can I add $data in constructor? - El Forum - 01-02-2010 [eluser]shinokada[/eluser] $this->data['mostsold'] or $this->$data['mostsold']? Don't I need $ in front of data? Can I add $data in constructor? - El Forum - 01-02-2010 [eluser]BrianDHall[/eluser] [quote author="shinokada" date="1262444791"]$this->data['mostsold'] or $this->$data['mostsold']? Don't I need $ in front of data?[/quote] Nope, just the first $ denotes a variable. You only use the second $ if you want something like this: Code: $this->data['mostsold'] = 10; Can I add $data in constructor? - El Forum - 01-10-2010 [eluser]veliscorin[/eluser] [quote author="Aken" date="1262397731"]You need to define those as a class variable. The way you have it now, $data only exists in the constructor function. Use: Code: class Example extends Controller { I am facing the same problem. I wish to use $data in the constructor to remove repeated code. And at the same time use $data in my functions. I figured out 2 ways.... The first is as you suggested. The other ways is to do this first in every function: Code: $data = $this->data; Is there any better way to do it? than repeat this line in all my functions? Can I add $data in constructor? - El Forum - 01-16-2010 [eluser]Aken[/eluser] If you aren't adding any additional data to that particular array in that particular function, you can just pass $this->data like normal. If you add any additional info to $this->data, that additional info will be present in another function if it is called within the same instance. If you want to use default data, then add some more on top of it, I would just define a local variable like you said ($data = $this->data ![]() |