If you're looking for a way to save time when you program, look no further. Creating functions lets you reuse code that you've used before without having to rewrite the whole thing. Keep reading to learn how.
You've used functions that take arguments. These arguments are variables that have been passed to the function as arguments when a function is executed. You can also use variables within a function using the global statement.
The global statementextends the scope of a variable. The term scope refers to the realm in which the variable can exist. For example, the scope of a variable that you create in a script exists throughout the life of that script. In other words, the variable can be used anywhere in the script, in the same way that environment variables such as $_SERVER['PHP_SELF'] exist throughout the server.
Functions create a new realm for variables to exist in. Function variables such as the arguments passed by a script, and variables defined within a function, exist only within that function and cannot be used outside of the function's realm. These kind of variables are called "local" variables with a "local" scope. In the same vein, the variables outside a function can only be passed to a function as an argument or by the use of the term "global."
The "global" statement makes a variable be the same outside and within the function. In effect a local variable with local scope is turned into a global variable with global scope. So, any changes made to this variable within a function are also passed on to the variable when it is used outside of the function.
The syntax of a global variable is:
function function_name($argument){
global $variable;
statements
}
As long as $variable exists outside of the function, it will also have the same value within the function. Here's a simple demonstration:
<?php $n1 = 2; $n2 = 2;
function Add() { global $n1, $n2;
$n2 = $n1+ $n2; }
Add();
echo $n2; ?>
The above outcome will be "4" because we declared $n2 and $n1 as global within the function, and that caused those "global" variables to reference the variables declared in the script.
Conclusion
Functions make it easy to code when you are working on large projects and also make your code more portable. Another thing to keep in mind about functions in general, is that their execution time is slower than if you'd just written it out. But you would not really notice it, especially if you are not a programmer. This is particularly true if you use classes in larger projects. We will be discussing classes in an upcoming article.