Tuesday, 18 December 2012

Episode 12: Using variables in functions



You can create and use a variable inside your function. Such a variable is called local to the function. However, the variable isn’t available outside of the function; it’s not available to the main script. If you want to use the variable outside the function, you have to make the variable global, rather than local, by using a global statement. For instance, the variable $name is created in the following function:

function format_name()
{
$first_name = “John”;
$last_name = “Smith”;
$name = $last_name, “.$first_name;
}
format_name();
echo “$name”;

These statements don’t produce any output. In the echo statement, $name doesn’t contain any value. The variable $name was created inside the function, so it doesn’t exist outside the function. You can create a variable inside a function that does exist outside the function by using the global statement. The following statements contain the same function with a global statement added:

function format_name()
{
global $name;
$first_name = “John”;
$last_name = “Smith”;
$name = $last_name, “.$first_name;
}
format_name();
echo “$name”;
Smith, John

You must make the variable global before you can use it. If the global statement follows the $name assignment statement, the script doesn’t produce any output. That is, in the preceding function, if the global statement followed the $name = statement, the function wouldn’t work correctly. Similarly, if a variable is created outside the function, you can’t use it inside the function unless it’s global. In the following statements, the only global
statement is inside the function:

$first_name = “John”;
$last_name = “Smith”;
function format_name()
{
global $first_name, $last_name;
$name = $last_name.”, “.$first_name;
echo “$name”;
}
format_name();

Because the code didn’t include a global statement outside the function, $last_name and $first_name inside the function are different variables than $last_name and $first_name created in the script outside the function. The variables $last_name and $first_name inside the function are created when you name them and have no values.



Written by “Shojib”.

No comments:

Post a Comment