include() vars within functions!

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
xtjdx
Forum Newbie
Posts: 5
Joined: Sun Oct 09, 2005 3:23 am

include() vars within functions!

Post by xtjdx »

Here is my dilemma!
I am including a file full of config vars.
My code is basically:

Code: Select all

<?
include_once('config.inc.php');
echo $randomvar;
function showvar()
{
echo $randomvar;
}
showvar();
?>
This will output the value of $randomvar once for the regular echo, but not in the function.
The content of config.inc.php is:

Code: Select all

<?
$randomvar = 'test';
?>
What's going on here?
Am I totally inept?
Thank you in advance for any help offered!
User avatar
blacksnday
Forum Contributor
Posts: 252
Joined: Sat Jul 30, 2005 6:11 am
Location: bfe Ohio :(

Re: include() vars within functions!

Post by blacksnday »

xtjdx wrote:Here is my dilemma!
I am including a file full of config vars.
My code is basically:

Code: Select all

<?
include_once('config.inc.php');
echo $randomvar;
function showvar()
{
echo $randomvar;
}
showvar();
?>
This will output the value of $randomvar once for the regular echo, but not in the function.
The content of config.inc.php is:

Code: Select all

<?
$randomvar = 'test';
?>
What's going on here?
Am I totally inept?
Thank you in advance for any help offered!

Code: Select all

<? include_once('config.inc.php');
function showvar($randomvar)
{
echo $randomvar;
}
showvar($randomvar);
?>
or

Code: Select all

<? include_once('config.inc.php');
function showvar()
{
global $randomvar;
echo $randomvar;
}
showvar()
?>

:)
xtjdx
Forum Newbie
Posts: 5
Joined: Sun Oct 09, 2005 3:23 am

Post by xtjdx »

Bahhhh that is going to be a whole lot of extra code. Thank you.
pilau
Forum Regular
Posts: 594
Joined: Sat Jul 09, 2005 10:22 am
Location: Israel

Post by pilau »

So what you mean is that functions can't call variables which were declared outside of them?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

pilau wrote:So what you mean is that functions can't call variables which were declared outside of them?
bingo. It's called variable scope.

http://php.net/language.variables.scope
xtjdx
Forum Newbie
Posts: 5
Joined: Sun Oct 09, 2005 3:23 am

Post by xtjdx »

Very interesting. I saw something about that and said "hey, that's probably my problem!" but fell asleep halfway into reading it.
Post Reply