Path: csiph.com!usenet.pasdenom.info!gegeweb.org!de-l.enfer-du-nord.net!feeder1.enfer-du-nord.net!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: "J.O. Aho" Newsgroups: comp.lang.php Subject: Re: Globalizing vars in class methods doesnt seem to work, var disappears after global, var is inaccessible in other methods/funcs Date: Sun, 05 Aug 2012 08:28:02 +0200 Lines: 58 Message-ID: References: <583b8426-bd2f-4d85-babb-a3c0630ef3fb@googlegroups.com> <183a6ce7-9ac7-4b98-9bc3-68d9eb895501@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Trace: individual.net Ji5/R90S41scPy2wKCmu6wAJvOO8+5VOMLHwdK3BsBDIwggPlQgn1QUleW0M1B9kQZ Cancel-Lock: sha1:xeRLenyHn9cP701NFyYCjkmKAzs= User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:13.0) Gecko/20120613 Thunderbird/13.0 In-Reply-To: <183a6ce7-9ac7-4b98-9bc3-68d9eb895501@googlegroups.com> Xref: csiph.com comp.lang.php:6724 On 05/08/12 06:08, J. Frank Parnell wrote: > On Saturday, August 4, 2012 11:45:35 AM UTC-7, Jerry Stuckle wrote: >> On 8/4/2012 2:24 PM, Jerry Stuckle wrote: > >> >> An addition option I forgot to mention - you could also use the >> >> singleton pattern as M. Strobel referenced. However, if you do, you >> >> should always have a default parameter in the call so you can use >> >> something other than the singleton when you need to. > > Ok, I read a little on the singleton, that does seem like a good way of doing it. What I wound up doing, before you guys replied, was just $this->var = 'something' and then doing $t->var where I needed that 'something'. Which I think make sense for OO? Because it is somewhat logical for 'something' to be part of my class, in my situation. Although 'something' is a different object, eg, an api class. My class is a child class of a controller in an MVCish framework. > > I just found out that this works > class test{ > function __construct(){ > $this->makevar(); > } > function makevar(){ > global $var; > $var = 'something';// actually, $var = new something(); > } > }//class > > $t = new test; > echo '
outside class: '.$var;//works And I assume would work in a unrelated function if I globalled it in there. > >> always have a default parameter in the call so you can use >> something other than the singleton when you need to > > not sure what this means class test { private $var = null; function __construct($invalue = null) { $this->var = $invalue; } } IMHO it's better to have functions if you want to manipulate values in a class, there are many ways to do it, but the simplest would just be: function getVar() { return $this->var; } function setVar($invalue) { // verify that the input is of the right form // then update the value $this->var = $invalue; } -- //Aho