Variables created outside of your function will only be availabe for use
outside the function. If you need a variable to be available for use
inside and outside of your functions we claim it to be a global variable. If you create a variable inside of
your functions it is only available inside that function. To make the
variables created more versatile and reusable you can set them as global. The three examples below will show variable scope in different scenarios.
Example of using global to set a variable's scope to be
wider and use inside and outside of functions:
<?php
$var1 = "Hello ";
function sampleFunction() {
// Set $var1 variable as global
global $var1;
// Now echo to the browser
echo "$var1 World <hr />";
}
// execute function to run
sampleFunction();
// Now echo to the browser again using variable created in our function
echo "$var1 World <hr />";
?>
Hello World
Hello World
Example of NOT being able to access a variable outside of a
function:
<?php
function sampleFunction() {
$var1 = "Hello ";
// Now echo to the browser
echo "$var1 World <hr />";
}
// execute function to run
sampleFunction();
// Now echo to the browser again using variable created in our function
echo "$var1 World <hr />";
?>
Hello World
World
Example of not being able to access a variable inside of a
function:
<?php
$var1 = "Hello ";
function sampleFunction() {
// Now echo to the browser
echo "$var1 World <hr />";
}
// execute function to run
sampleFunction();
// Now echo to the browser again using variable created in our function
echo "$var1 World <hr />";
?>
World
Hello World