On Fri, 26 Apr 2002, Liam Gibbs wrote: > I have a problem with my variables not being set. I have a file I use > for constants and functions, structured like so: > > $this = "this"; > $that = "that"; > . > . > . > function this() { > $h = $this; > $i = $that; > } > > function that() { > } > > Now, when I run this(), $this isn't set (even though it's above it in > the same file). I can pretty much guess (when running a function, it > won't parse through the whole file, just skips to that function), but I > was wondering if there is another solution. I'd hate to separate the > variable settings and the functions, but will if I have to.
(the following lesson applies to most programming languages these days) Each variable has what's called "scope", which defines the context in which it is visible. There is something called "global scope" which refers to all variables created outside of any function or object. Variables with global scope are then available anywhere outside of a function or object. Also, each function has its own "local scope". Variables created inside a function have scope local to that function and cannot be seen or referenced outside of that function. This is very good for programming, because it means you can re-use variables like $file and $str without having to worry that you are messing things up elsewhere in your program. Without scoping, writing a program of any serious size becomes a major pain: You have to keep making up longer and longer variable names, and your variables' contents keep getting changed behind your back. Your $this and $that are created with global scope. This is why they are not accessible within the functions this() and that(). When you referred to $this inside function this(), you created an entirely new variable $this with scope local to function this(). Obviously you need ways to move data in and out of functions. The preferred method is to pass them into functions as arguments and receive the results as the function's return value. For instance, try running this simple program: <? $this = "hello"; $that = my_function($this); print $that; function my_function($str) { print $str; return "I just said '$str'"; } ?> The other way to get variables into a function is to import them from the global scope. You do this with the keyword global, as follows: <? $this = "hello"; my_function(); function my_function(); { global $this; print $this; } ?> (in both examples I changed the variable and function names around to eliminate the human confusion caused by using 'this' and 'that' for both). miguel -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php