Adding parameters to a function in PHP
Our first function (writeMyName()) is a very simple function. It only writes a static string.
To add more functionality to a function, we can add parameters. A parameter is just like a variable.
You may have noticed the parentheses after the function name, like: writeMyName(). The parameters are specified inside the parentheses.
Example 1
The following example will write different first names, but the same last name:
<html>
<body>
<?php
function writeMyName($fname)
{
echo $fname . " Thomas.<br />";
}
echo "My name is ";
writeMyName("John");
echo "My name is ";
writeMyName("Wilson");
echo "My name is ";
writeMyName("Mariamma");
?>
</body>
</html>
The output of the code above will be:
My name is John Thomas.
My name is Wilson Thomas.
My name is Mariamma Thomas.
Example 2
The following function has two parameters:
<html>
<body>
<?php
function writeMyName($fname,$punctuation)
{
echo $fname . " Thomas" . $punctuation . "<br />";
}
echo "My name is ";
writeMyName("John",".");
echo "My name is ";
writeMyName("Wilson","!");
echo "My name is ";
writeMyName("Mariamma","...");
?>
</body>
</html>
The output of the code above will be:
My name is John Thomas.
My name is Wilson Thomas!
My name is Mariamma Thomas...
Back to Home
|