FunctionThe syntax of function is very similar to Javascript:
<?php
function abc() {
echo "I love PHP";
}
echo "Hello, World <br />";
abc();
?>
The output is:
Hello, World
I love PHP
You can put any PHP code into the function block. But you should keep in mind,
to use a function, you must call functin name with "()". In the above
the sample, we call the function:
abc();
We can pass parameters to a function:
<?php
function abc($count, $msg = "I love PHP") {
for($i = 0; $i < $count; $i++){
echo $msg . "<br />";
}
}
abc(5);
The output is that the value of $msg "I love PHP" will be displayed
for 5 times.
We can use the return statements to assign a variable's value
based on the results of the execution of a particular function. For example:
<?php
function compareNum($v1, $v2) {
if($v1 > $v2) {
return "Yes";
} else {
return "No";
}
?>
$anwser = compareNum(8, 10);
echo "Is 8 greater than 10? -- $answer!";
?>
The output will be:
Is 8 greater than 10? -- No!
|