Functions in PHP. Organizing You Code.

We have seen already how code can be organized into functions in JavaScript. In this lecture we discuss the same issue about PHP.

Defining and calling functions.

PHP allows us to group some code into functions, call these functions when we need them, and also keep these functions in separate files. To define a function in PHP we need to use the keyword function and give the new function a name. If we want this function to take any arguments we need to list these argument names inside the parenthesis after the function name. Note: even if a function doesn't take any arguments we still need to have parenthesis after the name:
function tax($salary)
{
    $tax = $salary/100 * 20;
    return $tax;
}

function html_header()
{
    print "<html>\n<head>\n <title>My web-site</title>\n</head>\n\n";
    print "<body>\n";
    return;
}
The keyword return used in the examples above is used to return a specific value from a function. If used alone (like in function html_header()) it denotes the end of the function, rather than returns a value.

If you need to provide several parameters to your function you need to separate them by commas.

function aftertax($salary, $TaxRate)
{
    $Salary = $salary - $salary/100 * $TaxRate;
    return $Salary;
}

Please note that functions aren't actually executed until called elsewhere in your PHP script. To call a function we need to use it's name. For example, the following line calls previously defined function aftertax() and stores its result into variable $payment:

$payment = salary(5000, 15);

We already know that we can have as many PHP scripts inside each PHP file as we want and we can call a new function from any of these scripts.

Passing values.

We have seen already how functions use parameters. The single items that we pass into functions are individually known as arguments. The difference between a parameter and an argument is that arguments are what go into the function call, while parameters are what are used in the function body. There are several ways to pass arguments to a function.

Passing by values.

The first method is the one we already used:
function tax($salary)
{
    $salary = $salary/100 * 20;
    return $salary;
}

$salary = 2500;
echo tax($salary); // will display 500
echo $salary;      // will display 2500
This process is known as passing an argument by value. No matter how we alter the value within the function, the value we have passed to it in $salary will remain the same.

Passing by reference

There is a second method which involves the passed value being changed inside the function. This is called passing an argument by reference. To indicate to PHP that you wish to use this method, you add an ampersand to the front of the variable you are passing:
function aftertax(&$salary, $TaxRate)
{
    $salary = $salary - $salary/100 * $TaxRate;
    return $salary;
}

$salary = 2500;
echo aftertax($salary, 20);   // will display 2000
echo $salary;                 // will display 2000
If a variable passed by reference was changed in a function that affects the variable value of the variable after the function call.

Setting default parameter values.

We can also set values of your parameters within the arguments themselves. This becomes the default value for when you don't specify any parameter:
function tax($salary=2500)
{
    $salary = $salary/100 * 20;
    return $salary;
}

echo tax();     // will display 500  since no argument is provided the default value 2500 is used
echo tax(3000); // will display 600
We can set default values for some of parameters, not all of them:
function aftertax($salary, $TaxRate=20)
{
    $Salary = $salary - $salary/100 * $TaxRate;
    return $Salary;
}

echo aftertax(3000);      // will display 2400 (second argument is not provided => the default value is used)
echo aftertax(3000, 10);  // will display 2700
If we don't set default values and don't pass all of the arguments across in the function call, then PHP will effectively pass a zero across for you (will bring a warning message as well). That is, if our function accepts two parameters, and we only pass it one in the call, then the one we didn't pass is set as zero:
function aftertax($salary, $TaxRate)
{
    $Salary = $salary - $salary/100 * $TaxRate;
    return $Salary;
}

echo aftertax(2500);  // will display 2500
This also applies to optional parameters, so if we make the first parameter optional as follows:
function aftertax($salary=2500, $TaxRate)
{
    $Salary = $salary - $salary/100 * $TaxRate;
    return $Salary;
}

echo aftertax(20);  // will display 20
PHP takes 20 as the first argument ($salary) and sets the second argument ($TaxRate) as zero. The default value 2500 is not used because it turns out we provided this argument.

One more thing about parameters.

What is wrong with the following code?
function aftertax(&$salary, $TaxRate)
{
    $salary = $salary - $salary/100 * $TaxRate;
    return $salary;
}

echo aftertax(2500, 20);
Function looks OK and it actually is. The problem is in the way we are calling this function. Since we specified that argument $salary is a variable passed by reference it has to be a variable. ALthough, in the echo statement we pass it as a constant number 2500 and this is exactly the place we are getting an error. The error occurs because our function supposed to change the value of the variable $salary and store it at the same location, but constant number does not have any location in memory. So, our function is not able to change and store a constant. Thus, the correct way to call this function would be:
$my_salary = 2500;
echo aftertax($my_salary, 20); 

Scope of variables.

Variables created outside a function still exist for the whole of the duration of the web page. This whole concept is termed scope. Variables inside a function are described as having local scope. Variables that retain their value throughout the lifetime of the page are described as having global scope.
$english = "Hello world!";                     // global variable

function translate($english)
{
    $french = "Bonjour Tout Le Monde!";        // local variable
    echo $english;                             // print the local $englich
    echo $french;                              // print the local $french
    return $french;
}

echo $english;                                 // print the global $english
echo $french;                                  // try to print local $french
translate("Privet, Mir!");

Using global variables inside functions.

Unlike many other languages global variables are not seen by default inside functions. If we need to access global variables from inside we have to declare them as global. We can do it using the global keyword.
$english = "Hello world!";                     // global variable

function translate()
{
    global $english;
    $french = "Bonjour Tout Le Monde!";        // local variable
    echo $english;                             // print the global $englich
    echo $french;                              // print the local $french
    return $french;
}

echo $english;                                 // print the global $english
echo $french;                                  // try to print local $french
translate("Privet, Mir!");

There is a different way to access global variables from inside a function. We can do it through the predefined $GLOBALS array. This is a string indexed array that contains the values of all global variables. The names of the variables (without $ sign) are the indexes of the array.

$english = "Hello world!";                     // global variable
function translate()
{
    $english = $GLOBALS["english"];            // create local $english with the same value as global one
    $french = "Bonjour Tout Le Monde!";        // local variable
    echo $english;                             // print the local $englich
    echo $french;                              // print the local $french
    return $french;
}

echo $english;                                 // print the global $english
echo $french;                                  // try to print local $french
translate("Privet, Mir!");

Please look at this example to see what are predefined global variables in PHP.

Getting local variables to retain their values.

What happens if we call the same function over and over again? Local variables inside the function will be recreated at every new call and will be forgotten when the function is completed. That is, a function has no memory about what happened before. There may be times though when you want the value of the variable to persist between function calls. Variables that persist between function calls are known as static variables. To make sure that our variable exists between calls, we need to add the keyword static before it.
function counter()
{
    static $counter = 0;
    return ++$counter;
}

echo counter();    // returns 1
echo counter();    // returns 2
echo counter();    // returns 3
echo counter();    // returns 4
Since variable $counter is declared to be static the assignment $counter=0 will be done only once at the very first time we call the function. In all other calls this function will remember the previous value of the variable.

Splitting code into different files.

If we created a set of useful functions and would like to use them in other scripts we do not need copy/paste them from script to script. We can create a separate file and put these functions there. To make them usable in a script we need to use PHP functions require() or include() that take name of the file as an argument and include the content of the file in the script.

The include() function is evaluated each time it is encountered and may be contained within loops or condition statements. The require() statement is not subject to any control structures. This means that files cannot conditionally included using require().

Here is a short example that shows how we can use these functions: Where files test_require.php, test_include_1.php, and test_include_2.php are:

test_require.php

test_include_1.php

test_include_1.php