I have a separate file where I include variables with thier set value. How can I make these variables global?
Ex. I have the value $myval
in the v
Using the global keyword in the beginning of your function will bring those variables into scope. So for example
$outside_variable = "foo";
function my_function() {
global $outside_variable;
echo $outside_variable;
}
Is there a reason why you can't pass the variable into your function?
myFunction($myVariable)
{
//DO SOMETHING
}
It's a far better idea to pass variables rather than use globals.
Inside the function, use the global
keyword or access the variable from the $GLOBALS[] array:
function myfunc() {
global $myvar;
}
Or, for better readability: use $GLOBALS[]
. This makes it clear that you are accessing something at the global scope.
function myfunc() {
echo $GLOBALS['myvar'];
}
Finally though,
Whenever possible, avoid using the global variable to begin with and pass it instead as a parameter to the function:
function myfunc($myvar) {
echo $myvar . " (in a function)";
}
$myvar = "I'm global!";
myfunc($myvar);
// I'm global! (in a function)
Same as if you declared the variable in the same file.
function doSomething($arg1, $arg2) {
global $var1, $var2;
// do stuff here
}
Use inside your function :
global $myval;
PHP - Variable scope