Returning Variables From Functions

Returning Variables From Functions

If you want to return a variable from a function, you have choices. The two methods discussed in this tutorial will be returning a global variable and returning a non-global variable.

Here is how the first code snippets works. The subtract function is called and it passes in 2 parameters. Then, the global modifier is used to make the $total variable have a global scope. After that, the $total variable is given a value, and finally, it is returned. As you can see, the variable behaves just as though it was created outside of the function and both echo statements are printed. If you did not have the global scope, the variable $total would be undefined and nothing would print.

function subtract($x,$y){
    global $total;
    $total = 101;

    return $total;

}

//prints the total
subtract(1,2);
echo "<br/>";

//prints the total
echo $total."<br/>";

if ($total == 101){
    echo "Hi";
}


Output

101
Hi


Returning Non-Global Variable

With example below, a variable is created and it is equal to the function and its parameters. In this case, the variable takes on the returned value from the subtract function.

function subtract($x,$y){
   // global $total;
    $total = 101;

    return $total;

}

//prints the total
$total = subtract(1,2);
echo "<br/>";

//prints the total
echo $total."<br/>";

if ($total == 101){
    echo "Hi";
}

Now that you have had some fun, you may want to expand on more PHP variable scope with PHP OOP. You can find PHP OOP tutorials here.