PHP functions are getting started. read about 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. Creating a PHP function is a code block that can be executed when needed. Create a PHP function: all "> <LINKhref =" http ://
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:
Function writeMyName (){
Echo "David Yang ";
}
WriteMyName ();
?>
Use PHP functions
Now, we need to use this function in the PHP script:
<? Php
Function 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:
<? Php
Function 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:
<? Php
Function 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
<? Php
Function add ($ x, $ y ){
$ Total = $ x + $ y;
Return $ total;
}
Echo "1 + 16 =". add (1, 16 );
?>
Output of the above code:
1 + 16 = 17