PHP provides over 700 built-in functions. PHP functions are divided into user-defined functions and system built-in functions. Built-in functions can be used directly. User-defined functions must be defined using the keyword function.
Custom Functions
A function is a set of independent program statements to implement a function. After writing a function into a function, you can easily use it as needed. Reasonable Use of functions can make our PHP programs more concise and easy to read, and more scientific.
Syntax
| The Code is as follows: |
Copy code |
Function function_name (arg1, arg2 ,......) { Function Code } |
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.
Function Parameters
The parameter function is to pass information to the function.
Example
Now, we need to use this function in the PHP script:
| The Code is as follows: |
Copy code |
<Html> <Body> <? Php Function writeMyName () { Echo "David Yang "; } Echo "Hello world! <Br/> "; Echo "My name is "; WriteMyName (); Echo ". <br/> That's right ,"; WriteMyName (); Echo "is my name ."; ?> </Body> </Html> output of the preceding code: Hello world! My name is David Yang. That's right, David Yang is my name. |
Example:
| The Code is as follows: |
Copy code |
<? Php Function city_name ($ city) { Echo "city name:". $ city; } City_name ("shanghai"); // you can call this function to output the "city name: shanghai" string. ?> You can specify a default value for a function parameter so that the default value is used when no parameter value is specified. <? Php Function city_name ($ city = "beijing ") { Echo "city name:". $ city; } $ Name = "shanghai "; City_name (); // The execution result is "city name: beijing" City_name ($ name); // The execution result is the output "city name: shanghai" ?> |