This is a discussion on Change variable with a function within the PHP General forums, part of the PHP Programming Forums category; Hello, I want to change a variable in a function. First I set a variable '$var1' to 'NO'. Then I ...
|
|||||||
| FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read |
|
|||
|
Hello,
I want to change a variable in a function. First I set a variable '$var1' to 'NO'. Then I call the function, within the function he have to set the variable to 'YES' Then I say: echo $var1; $var1 is still 'NO' :S <?PHP $var1 = 'NO'; setvar(); echo $var1; function setvar() { $var1 = 'YES'; } ?> Can a function set a variable outsite the function ? BTW, this is a little example script. Bert |
|
|||
|
Bertman wrote: > Hello, > > I want to change a variable in a function. > First I set a variable '$var1' to 'NO'. > Then I call the function, within the function he have to set the variable to > 'YES' > Then I say: echo $var1; > $var1 is still 'NO' :S > > <?PHP > $var1 = 'NO'; > > setvar(); > echo $var1; > > function setvar() { > $var1 = 'YES'; > } > ?> > > Can a function set a variable outsite the function ? > BTW, this is a little example script. To do it they way you have it in your example, you need to declate $var1 as a global inside the function. function setvar() { global $var1; $var1 = 'YES'; } The other way would be to have the function return a value: $var1 = setvar(); function setvar() { return('YES'); } Ken |
|
|||
|
Yeah great it works :D
function setvar() { global $var1; $var1 = 'YES'; } "Ken Robinson" <kenrbnsn@rbnsn.com> schreef in bericht news:1116002328.153250.318100@f14g2000cwb.googlegr oups.com... > > Bertman wrote: >> Hello, >> >> I want to change a variable in a function. >> First I set a variable '$var1' to 'NO'. >> Then I call the function, within the function he have to set the > variable to >> 'YES' >> Then I say: echo $var1; >> $var1 is still 'NO' :S >> >> <?PHP >> $var1 = 'NO'; >> >> setvar(); >> echo $var1; >> >> function setvar() { >> $var1 = 'YES'; >> } >> ?> >> >> Can a function set a variable outsite the function ? >> BTW, this is a little example script. > > To do it they way you have it in your example, you need to declate > $var1 as a global inside the function. > > function setvar() { > global $var1; > $var1 = 'YES'; > } > > The other way would be to have the function return a value: > > $var1 = setvar(); > > function setvar() { > return('YES'); > } > > Ken > |
![]() |
| Thread Tools | |
| Display Modes | |
|
|