Variables created within a function are not avaliable to the rest of the script and visa-versa. For example, in the previous example, I used echo() to output $rgb to the browser. If I had not included the echo in the function. $rgb would have been a local variable. Local variables are created within a function, used within a function and are not available to the rest of the script. If for example, I left out the echo() statement:
<?
function rgb2hex($r, $g, $b)
{
$r=dechex($r);
$g=dechex($g);
$b=dechex($b);
if ( strlen("$r") == 1 )
{ $r = "0" . "$r"; }
if ( strlen("$g") == 1 )
{ $g = "0" . "$g"; }
if ( strlen("$b") == 1 )
{ $b = "0" . "$b"; }
$rgb = "$r$g$b";
}
?>
then tried to output $rgb in the form,
<input type="text" value="<? echo "$rgb"; ?>" />
nothing would be output because $rgb is a local variable in a function. You can make a varable inside a function available to the rest of the script by making it a global variable using the global statement:
global $rgb;
$rgb = "$r$g$b";
The same is true for variables created outside of a function. If you want a function to use a variable created outside if it, you need to make it a global variable first.
<?
function add( $x, $y )
{
$answer = $x+$y+$z;
return ;
}
$z = 10;
echo add(1,2); # outputs 3
?>
The example above outputs 3, not 13 because $z in not a global variable. The next example outputs 13 because the function declares $z to be a global variable.
<?
function add( $x, $y )
{
global $z;
= $x+$y+$z;
return $answer;
}
$z = 10;
echo add(1,2); # outputs 13
?>
You can declare more than one variable to be global with one global statement:
global $var1, $var2, $var3;
Using global variables can lead to confusion so you want to avoid using them as much as you can. If you return to a script after not looking at it for months, you may unknowingly use a new variable with the same name as a global. User defined functions should be self sufficient. All of the arguments that it is supposed to use should be listed when you make it and it should not need any more than those listed.
|
|
|