Re: Variable scope

From: Date: Sat, 04 May 2002 17:14:36 +0000
Subject: Re: Variable scope
References: 1 2 3  Groups: php.general 
Request: Send a blank email to php-general+get-96068@lists.php.net to get a copy of this message
On Friday 15 March 2002 00:34, George Nicolae wrote: > "Jason Wong" <php-general@gremlins.com.hk> wrote in message > news:php.general-96048@news.php.net... > > > On Thursday 14 March 2002 21:53, George Nicolae wrote: > > > I have the following code: > > > > > > <? > > > function a($var_a) > > > { > > > b(); > > > } > > > > > > function b() > > > { > > > global $var_a; > > > echo $var_a; > > > } > > > > > > a("hello word!"); > > > ?> > > > > > > why function b() don't echo anything? > > > > Because $var_a has not, at any point, been defined in the global scope. > > how i declare $var_a as global? Strictly speaking, in php you don't. Any variable declared outside of a function is what can be loosely called "global". To access such variables inside a function you must tell PHP you want to use the global version of that variable. $doo = 'dah'; $foo = 'bar'; a(); function a() { global $doo; echo $doo; # displays 'dah'; echo $fool # displays nothing. } In your code above, you haven't defined $var_a anywhere outside of a function. Thus it is a local variable that only exists inside function a(). That is why function b() doesn't see it. > > > can I resolve this problem without > > > calling b($var_a)? > > > > I'm curious as to what you're trying to achieve. Could you enlighten me? > > I have a big(=many lines) function "a()" and a little one "b()". I call > function "b()" from function "a()" and alsow from many other php files. I > need to midify the function "b()" without modify any other php files. > That's why I don't want to use b($var_a). The easiest solution I can see right now is to explicitly define $var_a. -- Jason Wong -> Gremlins Associates -> www.gremlins.com.hk Open Source Software Systems Integrators * Web Design & Hosting * Internet & Intranet Applications Development * /* The use of anthropomorphic terminology when dealing with computing systems is a symptom of professional immaturity. -- Edsger Dijkstra */

« previous php.general (#96068) next »