Reputation: 3539
This is blowing my mind...
I've got a standalone PHP file, and a simple function with a global var.
<?php
$var = 4;
function echoVar()
{
echo $var;
}
echoVar();
?>
When I call echoVar()
nothing is returned... However if I place the $var
inside the function it will return 4.
What's going on here? Shouldn't $var
be global in this case?
Upvotes: 1
Views: 157
Reputation: 9444
If a variable is set outside of a function, it's not visible inside that function. To access it, you must declare it global with the global
keyword. This is called a scope.
<?php
$var = 4;
function echoVar() {
global $var;
echo $var;
}
echoVar();
Note: This is generally considered bad practice. Read this for more information.
A good alternative would be to pass in the variable as an argument:
<?php
$var = 4;
function echoVar($var) {
echo $var;
}
echoVar($var);
Upvotes: 5
Reputation: 3288
Just going to clarify since everyone seems to be posting mostly rubbish.
global $var;
This is how it "should" be done.
<?php
$var = 4; //set initial input var this is external to the function
function echoVar($internalvar) { /*notice were accepting $var as $internalvar I'm doing this to clarify the different variables so you don't end up getting confused with scope $internalvar is local to the function only and not accessible externally*/
return $internalvar; //now we pass the function internal var back out to the main code we do this with return you should never echo out your output inside the function
}
echo echoVar($var); //call function and pass $var in as an arguement
?>
Upvotes: 0
Reputation: 395
When you call any function it's create local variable so you have to pass argument in calling function part.
$var = 4;
function echoVar($var)
{
echo $var;
}
echoVar($var);
Upvotes: 0
Reputation: 507
You can either have $var as an argument, like this:
$var = 4;
function echoVar($var)
{
echo $var;
}
echoVar($var);
or use global, like this:
$var = 4;
function echoVar()
{
global $var;
echo $var;
}
echoVar();
Upvotes: 0
Reputation: 8074
Lots of options here... like
<?php
$var = 4;
function echoVar($var)
{
echo $var;
}
echoVar($var);
?>
or
<?php
$var = 4;
function echoVar()
{
global $var;
echo $var;
}
echoVar();
?>
Upvotes: 3