linuxStat PHP Documentation
Functions
A PHP function is a block of PHP code with the following structure:
function fname($param1, $param2)
{
PHP Code 1
}
When the function named fname is called, PHP Code 1 enclosed by
the braces { } is executed.
The two variables $param1, $param2 listed within the parentheses
( )
are called parameters.
A function call should provide the value of the two parameters.
Example:
function addTwoNumbers($left, $right)
{
$sum = $left + $right; // Line 1
return $sum; // Line 2
}
Line 1 adds the two parameters and assigns the result to the variable $sum.
Line 2 returns the result to the caller of the function.
An example function call of addTwoNumbers is the following:
$sumOfFiveAndSeven = addTwoNumbers(5, 7);
The above line of code calls addTwoNumbers and assigns 5 to $left and 7 to $right.
The result returned by addTwoNumbers is assigned to the variable $sumOfFiveAndSeven.
The above example embedded in an HTML document:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/transitional.dtd">
<html>
<head>
<meta http-equiv=Content-Type content="text/html; charset=us-ascii">
<title>Executed on Dell Server, Intel Processor, created on HP laptop</title>
</head>
<body bgcolor="#6B7E23" text="#FFFF00" lang=EN-US>
<?php
# Example of a function
function addTwoNumbers($left, $right)
{
$sum = $left + $right; // Line 1
return $sum; // Line 2
}
$sumOfFiveAndSeven = addTwoNumbers(5, 7);
print "The sum of 5 and 7 is $sumOfFiveAndSeven";
?>
</body>
</html>
A function can have any number of parameters including no paramenter.
It is not necessary for a function to return a value.
Click the following link to execute the above PHP code
by my server's PHP interpreter.
Try the above example Next Index