PHP Functions
The real power of PHP comes from its functions.
In PHP, providing more than 1000 built-in functions.
PHP built-in function
For a complete reference manual and all instances of array functions, visit our PHP Reference .
PHP Functions
In this chapter, we will show you how to create your own functions.
To run the script when the page loads, you can put it in the function.
Function is performed by calling the function.
You can call a function in any position on the page.
Create a PHP Function
Function is performed by calling the function.
grammar
{
要执行的代码;
}
PHP function guidelines:
- The name of the function should prompt its function
- Function names begin with a letter or an underscore (can not start with a number)
Examples
A simple function when it is invoked my name can be output:
<body>
<?php
function writeName()
{
echo "Kai Jim Refsnes";
}
echo "My name is ";
writeName();
?>
</body>
</html>
Output:
PHP Functions - Adding parameters
In order to add more functionality to a function, we can add parameters. Similar arguments variable.
Parameters after the function name has a designated parenthesis.
Example 1
The following examples will output a different name, but the name is the same:
<body>
<?php
function writeName($fname)
{
echo $fname . " Refsnes.<br>";
}
echo "My name is ";
writeName("Kai Jim");
echo "My sister's name is ";
writeName("Hege");
echo "My brother's name is ";
writeName("Stale");
?>
</body>
</html>
Output:
My sister's name is Hege Refsnes.
My brother's name is Stale Refsnes.
Example 2
The following function has two parameters:
<body>
<?php
function writeName($fname,$punctuation)
{
echo $fname . " Refsnes" . $punctuation . "<br>";
}
echo "My name is ";
writeName("Kai Jim",".");
echo "My sister's name is ";
writeName("Hege","!");
echo "My brother's name is ";
writeName("Stale","?");
?>
</body>
</html>
Output:
My sister's name is Hege Refsnes!
My brother's name is Stale Refsnes?
PHP Functions - Return Value
To make the function returns a value, use the return statement.
Examples
<body>
<?php
function add($x,$y)
{
$total=$x+$y;
return $total;
}
echo "1 + 16 = " . add(1,16);
?>
</body>
</html>
Output: