Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

PHP variable isn't being passed between files 1

Status
Not open for further replies.

bpw89

Programmer
Dec 17, 2006
11
US
Hi all,
I'm a web designer, and I've been working on some very simple PHP lately. I hope that someone can help me with a strange problem:
I've got a file (index.php) in which I've defined a variable, and called another file. It look something like this:
$name="home";
require("template.php");
That file (template.php) has some xhtml, then it calls a third file:
require("menu.php");
Inside menu.php, I'm trying to use the variable $name from the first file, except it doesn't work. Let me be more specific. I was trying to use $name in a function to add another class to a link. It wasn't adding the class, so I tried echo $name; and found that it doesn't output anything.

My question: is it correct that the variable is supposed to be passed from one file to the next? i.e. shouldn't this work?
If so, can anyone suggest what the problem might be, or do I need to supply more details?

Thanks so much.
 
You can try the following, on index.php you create hiddenfields and set the value of those according to the variables you have on that page, then in menu.php you set the variable values there by requesting the hiddenfield values in index.php.

 
bpw89 said:
I was trying to use $name in a function
There's your problem. There is no problem using a variable in an included script, but you can't just use a variable from the global scope inside a function. A function has its own local scope, so if you use $name in a function, PHP will look for a $name declared inside that function.

To use your variable inside a function, you have to either add a global declaration or use the $GLOBALS array. You would do that like this:
Code:
# Using global keyword
function foo() {
   global $name;
   echo $name;
}
Code:
# Using $GLOBALS
function foo() {
   echo $GLOBALS['name'];
}
Both of these examples will use the same $name declared in your first script.
 
You can also pass the variable to the function when you call it.

Code:
function myfunction($variabletopass){
echo $variabletopass;
}

.
.
.

myfunction($name);

What this does is ti passes the value of $name to the inside of the function. You can then use it by accessing the variable specified in the function definition. $variabletopass in this case



----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
Thanks for everyone's input, using global $name; did the trick!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top