Real world applications are usually much larger than the examples above.
In has been proven that the best way to develop and maintain a large program
is to construct it from smaller pieces (functions) each of which is more
manageable than the original program.
A function may be defined using syntax such as the following:
<?php
function addition($val1, $val2)
{
$sum = $val1 + $val2;
return $sum;
}
?>
Using Default Parameters
When calling a function you usually provide the same number of argument
as in the declaration. Like in the function above you usually call it like
this :
$result = addition(5, 10);
But you can actually call a function without providing all the arguments
by using default parameters.
<?php
function repeat($text, $num = 10)
{
echo "<ol>\r\n";
for($i = 0; $i < $num; $i++)
{
echo "<li>$text </li>\r\n";
}
echo "</ol>";
}
// calling repeat with two arguments
repeat("I'm the best", 15);
// calling repeat with just one argument
repeat("You're the man");
?>
Function repeat() have two arguments
$text and $num. The $num
argument has a default value of 10. The first call to repeat()
will print the text 15 times because the value of $num
will be 15. But in the second call to repeat()
the second parameter is omitted so repeat() will
use the default $num value of 10 and so the text
is printed ten times.
Returning Values
Applications are usually a sequence of functions. The result from one function
is then passed to another function for processing and so on. Returning a value
from a function is done by using the return statement.
<?php
$myarray = array('php tutorial',
'mysql
tutorial',
'apache
tutorial',
'java
tutorial',
'xml
tutorial');
$rows = buildRows($myarray);
$table = buildTable($rows);
echo $table;
function buildRows($array)
{
$rows = '<tr><td>' .
implode('</td></tr><tr><td>',
$array) .
'</td></tr>';
return $rows;
}
function buildTable($rows)
{
$table = "<table cellpadding='1' cellspacing='1'
bgcolor='#FFCC00'
border='1'>$rows</table>";
return $table;
}
?>
You can return any type from a function. An integer, double, array, object,
resource, etc.
Notice that in buildRows() I use the built
in function implode(). It joins all elements
of $array with the string '</td></tr><tr><td>'
between each element. I also use the '.' (dot)
operator to concat the strings.
You can also write buildRows() function like
this.
<?php
...
function buildRows($array)
{
$rows = '<tr><td>';
$n =
count($array);
for($i = 0; $i < $n - 1; $i++)
{
$rows
.= $array[$i] . '</td></tr><tr><td>';
}
$rows .= $array[$n - 1] . '</td></tr>';
return $rows;
}
...
?>
Of course it is more convenient if you just use implode().