Jump to content

Passing variables inside of a function from include() file...


anselk

Recommended Posts

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

Link to comment
Share on other sites

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
?>

Link to comment
Share on other sites

I declared it as global before the function and it didnt work.. didnt think to declare it as global inside.. :P 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.  ;-)

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.