Re: classes and variable scope

From: Date: Wed, 01 Dec 2004 21:28:45 +0000
Subject: Re: classes and variable scope
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-203273@lists.php.net to get a copy of this message
Josh Howe wrote: > > Hi all, > > If I have the following code: > > $some_global_variable; > > Class foo { > > Function test() { > set_global(); > echo $some_global_variable; > } > > Function set_global () { > $some_global_variable = "abcd"; > echo $some_global_variable; > } > } > > The first echo statement (the one inside the set_global function) prints > "abcd", but the second prints nothing. How can I set the value of > $some_global_variable inside the set_global function so that it sticks? > I'm using PHP 4.3.3. Choice 1: Declare it global in both functions. function test() { global $some_global_variable; } function set_global() { global $some_global_variable; } Choice 2: Use a member variable instead. function test(){ echo $this->some_global_variable; } function set_global() { $this->some_global_variable = 'abcd'; } Choice 3: Spend more time figuring out why you need a global variable, who needs this variable, why they need this variable, and re-structure your code so that you don't really need a global variable. :-) -- Like Music? http://l-i-e.com/artists.htm

« previous php.general (#203273) next »