include outside of a function

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
defx
Forum Commoner
Posts: 36
Joined: Mon Feb 16, 2004 11:50 pm
Location: Florida, USA

include outside of a function

Post by defx »

Is it possible to include a file, then later inside of a function, use a variable listed inside the included file? I tried it and it said that my variable was not definied. so i ended up having to include the file in the function.
User avatar
Dr Evil
Forum Contributor
Posts: 184
Joined: Wed Jan 14, 2004 9:56 am
Location: Switzerland

Post by Dr Evil »

Could you show me some code?
defx
Forum Commoner
Posts: 36
Joined: Mon Feb 16, 2004 11:50 pm
Location: Florida, USA

Post by defx »

what I did is i created a file called cfg.php:

Code: Select all

<? $var1 = "variable 1"; ?>
then in a seperate file:

Code: Select all

<? include ("cfg.php");

Function function1()
{
echo "$var1";
}
?>
and it did not work :o
mikegotnaild
Forum Contributor
Posts: 173
Joined: Sat Feb 14, 2004 5:59 pm

Post by mikegotnaild »

good question
User avatar
markl999
DevNet Resident
Posts: 1972
Joined: Thu Oct 16, 2003 5:49 pm
Location: Manchester (UK)

Post by markl999 »

You would have to do :

Code: Select all

<? include_once 'cfg.php'; 

function function1() 
{ 
    global $var1;
    echo $var1; 
} 
?>
User avatar
Dr Evil
Forum Contributor
Posts: 184
Joined: Wed Jan 14, 2004 9:56 am
Location: Switzerland

Post by Dr Evil »

Thanks Mark 'Connery' 999 beat me to it.
Post Reply