Using Functions
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:
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.
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.
0 comments:
Post a Comment