0% found this document useful (0 votes)
10 views11 pages

Chapter 5 Functions

Uploaded by

abaasmuuse
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
10 views11 pages

Chapter 5 Functions

Uploaded by

abaasmuuse
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 11

Chapter 5 Functions in PHP

Functions are sections of code that are defined by the user to perform a specific task. Functions

can take values called arguments as input, perform some operations, and then may return
another value. The function transfers any argument values into new variables, called
parameters, which can then be used within the function. A function will be executed by a call to
the function.

Defining and Calling Functions

A user defined function declaration starts with the word "function":

Syntax

function functionName ( ) {
code to be executed;
}

A function name can start with a letter or underscore (not a number). Give the function a name
that reflects what it does. Remember that function names are NOT case-sensitive.

To define a function, you have to give it a name. To do this, you use the keyword function,
followed by the function name. Any parameter names are listed in parentheses after the function
name. The code that forms the body of the function is placed in braces after the parameters.

Example 4.1

<?php
function writeMsg ( ) {
echo "Hello world!";
}
writeMsg ( ); // call the function
?>

1
Output: Hello world!

The opening curly brace ( { ) indicates the beginning of the function code and the closing curly
brace ( } ) indicates the end of the function. The function, writeMsg ( ), outputs "Hello world!".
To call the function, just write its name. You can call a function as many as you wish.

Example 4.2 Let us have an example that takes gross salary, then calculates the tax, and net
salary.

<?php
function tax ($salary)
{
$tax = $salary * 0.05;
$netSalary = $salary - $tax;
echo "Gross salary = $$salary";
echo "<br>Tax = $$tax";
echo "<br>Net salary = $$netSalary";
}
tax (500);
?>
Output: Gross salary = $500

Tax = $25

Net salary = $475

Function Arguments

Information can be passed to functions through arguments/parameters. An argument is just like a


variable. Arguments are specified after the function name, inside the parentheses. You can add as
many arguments as you want, just separate them with a comma.

2
Example 4.3 Write a function that calculates factorial of a number.

<?php
function factorial ($a) {
$fact = 1;
for ($i = 2 ; $i <= $a; $i++)
$fact *= $i;
echo "<br>Factorial of $a is : $fact";
}
factorial (5);
?>

Output: Factorial of 5 is : 120.

Example 4.4 convert decimal number to binary.

<?php
function decToBin ($x) {
$i = 0;
echo "<br>Binary of $x = ";
while ($x > 1)
{
$bin[$i] = $x % 2;
$x = $x / 2;
$i++;
}
for ($i = count ($bin); $i >= 0; $i--)
echo $bin[$i];
}
decToBin (10);
?>

3
Output: Binary of 10 = 1010.

Default Argument Value

You can set default argument to a function, just supply the default value in the parameter. For
example, function decToBin ($x = 12). When you call the function you omit the argument like
decToBin ( ); and it will take the default argument 12. In this case the output will be: Binary of
12 = 1100.

Returning values

To let a function return a value, use the return statement. Study the following example.

Example 4.5

function factorial ($a) {


$fact = 1;
for ($i = 2 ; $i <= $a; $i++)
$fact *= $i;
return "Factorial of $a = $fact";
}
echo factorial (5); // Print the returned value directly
$x = factorial (6); // Assign the returned value to a variable
echo $x;

Output: Factorial of 5 = 120

Factorial of 6 = 720

4
Assigning the Value Returned by Functions to Variables
Functions return a value, so it should follow that you are able to assign the value returned by a
function to a variable, and indeed you can. You just do it as follows:

function number_of_hits ( ) {
return 1000;
}
$HitCounter = number_of_hits ( );
echo $HitCounter;

Our variable $HitCounter would then be able to store whatever the function number_of_hits ( )
returned. You can then place the variable within the brackets of the switch ( ) statement.

Example 4.6

<?php
$HitCounter = number_of_hits ( );
switch ($HitCounter)
{
case $HitCounter < 100:
echo "Not many hits this week";
break;
case $HitCounter < 1000:
echo "Some hits this week";
break;
case $HitCounter < 10000:
echo "Loads of hits this week";
break;
}
?>
5
The function is run once, and depending on the outcome, we perform a difference action.

Passing Values to Functions


We have already described 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 in the function call, while parameters are what are used
in the function body. We have not examined this process in any detail and we need to look at it
further as there are actually two ways to pass arguments into our functions, and depending on
which method you use, it could yield a different result.

Passing by Value
The first method is the one we have already used. Our tax example required us to pass the $Sal
variable into it. If we pull it slightly, so that it physically alters the contents of the $Sal variable,
we can use it to illustrate the difference between the two methods.

<?php
function tax ($Salary)
{
$Salary = $Salary - (($Salary/100)*20);
return $Salary;
}
$Sal = 2500;
echo (tax($Sal)); // This will display 2000
echo "<br>$Sal"; // This will display 2500
?>

6
This does not alter our earlier example in anyway, as the two echoed values would still be
different.

What we have done is pass the value of the variable as an argument to the function. In this case
the number 2500 was passed, so inside the function it is as though a new variable, also called
$Salary, was created and given the value 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 $Sal variable will remain the same, so if you echo
the contents of $Sal after running the function, it will still be 2500. The function is only
outputting the figure we have calculated which is 2000, it is not doing anything else with it. This
is the default process that you will use when passing variables to functions. What happens if you
want the variable $Sal to actually hold the new figure you have just calculated?

Passing by Reference
There is the second method that we have not seen so far 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.

<?php
function tax (&$Salary)
{
$Salary = $Salary - (($Salary/100)*20);
return $Salary;
}
$Sal = 2500;
echo (tax($Sal)); // This will display 2000
echo "<br>$Sal"; // This will display 2000
?>

7
In which case, the actual contents of the $Sal variable are changed in this example, so that the
$Sal variable will now contain the value 2000, and you can echo the content of the $Sal variable
after the calculation to the screen.

Scope of Variables
Variables inside functions do not necessarily exist outside of them. In fact we need to introduce
the lifetime of a variable. The lifetime of a variable is the span from the moment a variable is
created to the moment it ceases to exist. Normally for a variable this is the duration of a web
page. However, when using variables inside functions, this is not necessarily true. It might just
be for the duration of the function that the variable lasts. The function is called, and the variables
inside come into existence. You get to the end of the function, and these variables are closed
down. Any reference to them outside of the function is invalid, as they no longer have any
values.

Global and Local 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.

Let us see an example of both of these in action. The following code displays a welcome
message either in Somali or in English:

$WelcomeMessage = "Good Afternoon"; // Global variable


function translate_greeting($WelcomeMessage)
{
$WelcomeMessage = "Galab Wanaagsan"; // Local variable
return $WelcomeMessage;
}
translate_greeting($WelcomeMessage);

8
echo $WelcomeMessage; // Global variable
Output: Good Afternoon

The first occurrence of the $WelcomeMessage sets it to the value "Good Afternoon". This is our
global variable. Inside our function we set $WelcomeMessage to "Galab Wanaagsan", and then
run the function – $WelcomeMessage is a local variable. If you were to run this code, the words
that would be displayed on your web page would be "Good Afternoon". This is because the
variable inside the function is in effect a completely different variable; it is local to the function
that contains it.

Using Global Variables Inside Functions


Conversely, if we were to display the contents of $WelcomeMessage variable inside our function
it would display nothing because $WelcomeMessage does not exist inside the function.

<?php
$WelcomeMessage = "Good Afternoon";
function translate_greeting($SomaliMessage)
{
echo $WelcomeMessage; // Prints nothing
$SomaliMessage = "Galab Wanaagsan";
return $SomaliMessage;
}
translate_greeting($WelcomeMessage);
echo $WelcomeMessage; // Prints Good Afternoon
echo $SomaliMessage; // Prints nothing
?>
Output: Good Afternoon

This makes sense – what happens if we have a local variable inside the function with the same
name as a global variable outside the function? We have to have some way of identifying global

9
variables because we need to ensure that it is the same variable, and does not just share the same
name. There are two ways of doing this. The first is shown below:

<?php
$WelcomeMessage = "Good Afternoon";
function translate_greeting($SomaliMessage)
{
global $WelcomeMessage;
echo $WelcomeMessage; // Prints Good Afternoon
$SomaliMessage = "Galab Wanaagsan";
return $SomaliMessage;
}
translate_greeting($WelcomeMessage);
echo "<br>$WelcomeMessage"; // Prints Good Afternoon
echo $SomaliMessage; // Prints nothing
?>
Output: Good Afternoon

Good Afternoon

In our function above, we have declared $WelcomeMessage to be a global variable. As we saw


earlier, if we echoed $WelcomeMessage inside the function without declaring it global, it
contained nothing because it was a local variable, and as such was undefined. Now, our echo ( )
command displays "Good Afternoon" as expected because the variable is global in scope.

Secondly, PHP can also achieve the same thing with the use of the $GLOBALS array. To
display the contents of the global variable within the function using the $GLOBALS array we
say the following:

10
<?php

$WelcomeMessage = "Good Afternoon";

function translate_greeting($SomaliMessage)

echo $GLOBALS["WelcomeMessage"];

echo ("<br>");

$SomaliMessage = "Galab Wanaagsan";

return $SomaliMessage;

translate_greeting($WelcomeMessage);

echo $WelcomeMessage;

echo $SomaliMessage;

?>

Output: Good Afternoon

Good Afternoon

In both examples you would see the message "Good Afternoon" displayed twice. This is because
we display it once inside the function and once outside it. Of course the variable
$SomaliMessage still displays nothing, because we only echo it outside the function.

The global keyword is very simple to understand, but the $GLOBALS array is slightly less so.

11

You might also like