anselk Posted October 27, 2010 Share Posted October 27, 2010 I am trying to pass a variable from inside of a function in a file that is included eg include.php <? function noms(){ $foobar = "apples"; } ?> main.php <? include("include.php"); noms(); echo "these ". $foobar. " are most delicious... OM NOM NOM"; ?> I am essentially using a include file for a mysql connection and based on the connection outcome i am either setting a value to true or false. It prints "Connected succesfully" and what not just fine, but, after that it wont pass on the variables data. I know its the function because, it passes the data if i put the variable before the function... i just dont get it.. any help would be great. Thanks. Ansel Quote Link to comment Share on other sites More sharing options...
naodai Posted October 27, 2010 Share Posted October 27, 2010 variable scope ,i think u will not understand that. look this link , it can help u. http://php.net/manual/en/language.variables.scope.php Quote Link to comment Share on other sites More sharing options...
mds1256 Posted October 27, 2010 Share Posted October 27, 2010 change to this include: <? function noms() { $foobar = "apples"; return $foobar; } ?> main: <? include("include.php"); echo "these ". noms(). " are most delicious... OM NOM NOM"; ?> that should work, use the return statement within the function have been advised (from people on this site) not to use global variables.... What i am doing when needing to return multiple variables from a function is to return an array of variables needing to be accessed, then pull back the array with the required index when needed. e.g. <?php function test() { $a = 5; $b = 10; $arr = array($a, $b); return $arr; } $returnedArr = test(); echo $returnedArr[0]; echo "<br/>"; echo $returnedArr[1]; echo ?> Quote Link to comment Share on other sites More sharing options...
anselk Posted October 27, 2010 Author Share Posted October 27, 2010 I declared it as global before the function and it didnt work.. didnt think to declare it as global inside.. ty I now realize that i have to define the variable first, not just as a global. (used to be good at php, came back forgot, but remember stuff still... so i think i get my self in more trouble. guh!) sweet, ty! FYI for anyone else, here is how it goes, on your included page, do your variable like normal $foobar = blah; function blah(){ global $foobar; // this makes it global to use now, even within the function you can just use $foobar } other page just call it like normal. <3 to all who helped. TY TY to mds1256 also, but i want it this way for a reason. never seen it done that way though. ;-) Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.