Returning Global Variables

You can also give a function access to an externally created variable by declaring it a global variable from within the function. The global keyword followed by the variable name gives every part of your code full access to it.

<?php
$a1 = "first name";
$a2 = "second name";
$a3 = "third name";
echo $a1 . " " . $a2 . " " . $a3 . "<br />";
fix_names();
echo $a1 . " " . $a2 . " " . $a3;
function fix_names()
{
global $a1; $a1 = ucfirst(strtolower($a1));
global $a2; $a2 = ucfirst(strtolower($a2));
global $a3; $a3 = ucfirst(strtolower($a3));
}
?>

Now you don’t have to pass parameters to the function, and it doesn’t have to accept them. Once declared, these variables remain global and available to the rest of your program, including its functions.

If at all possible, in order to retain as much local scope as possible, you should try returning arrays or using variables by association. Otherwise, you will begin to lose some of the benefits of functions.