PHP functions. The real power of PHP comes from its functions. PHP provides over 700 built-in functions. In this tutorial, we will show you how to create your own functions. The real power of PHP comes from its functions.
PHP provides over 700 built-in functions.
PHP functions
In this tutorial, we will explain how to create your own functions.
Create a PHP function
A function is a code block that can be executed when needed.
Create a PHP function:
All functions start with the keyword "function ()".
Name function-the function name should prompt its function. The function name must start with a letter or underscore.
Add "{"-the section after the opening curly braces is the function code.
Insert function code
Add a "}"-the function ends by closing curly braces.
Example
A simple function outputs my name when it is called:
Use PHP functions
Now, we need to use this function in the PHP script:
<?phpfunction writeMyName() { echo "David Yang"; }echo "Hello world! ";echo "My name is ";writeMyName();echo ". That's right, ";writeMyName();echo " is my name.";?> |
Output of the above code:
Hello world!My name is David Yang.That's right, David Yang is my name. |
PHP functions-add parameters
Our first function is a very simple function. It can only output one static string.
You can add parameters to add more functions to the function. The parameter is similar to a variable.
You may have noticed that the function name is enclosed in parentheses, such as writeMyName (). Parameters are defined in brackets.
Example 1
In the following example, different names are output, but the surnames are the same:
<?phpfunction writeMyName($fname) { echo $fname . " Yang. "; }echo "My name is ";writeMyName("David");echo "My name is ";writeMyName("Mike");echo "My name is ";writeMyName("John");?> |
Output of the above code:
My name is David Yang.My name is Mike Yang.My name is John Yang. |
Example 2
The following functions have two parameters:
<?phpfunction writeMyName($fname,$punctuation) { echo $fname . " Yang" . $punctuation . " "; }echo "My name is ";writeMyName("David",".");echo "My name is ";writeMyName("Mike","!");echo "My name is ";writeMyName("John","...");?> |
Output of the above code:
My name is David Yang.My name is Mike Yang!My name is John Yang... |
PHP function-return value
Functions can also be used to return values.
Example
<?phpfunction add($x,$y) { $total = $x + $y; return $total; }echo "1 + 16 = " . add(1,16);?> |
Output of the above code:
The real power of http://www.bkjia.com/PHPjc/446729.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/446729.htmlTechArticlePHP comes from its function. PHP provides over 700 built-in functions. In this tutorial, we will show you how to create your own functions ....