PHP function

This section describes

PHP user-defined functions

  • Function definition and invocation
  • Function parameters
  • Function return value

1. PHP function classification

(1) PHP built-in functions

  • Existing functions provided by PHP

(2) PHP user-defined functions

  • Functions defined by the user

2. PHP User-defined functions

(1)

  • Users can encapsulate repetitive code as functions.
  • The function does not execute immediately when the page loads.
  • Functions are executed only when they are called.

(2) Definition and invocation

  • User-defined functions start with function and have the following syntax:
    • No arguments:
      • function functionName() {the code being executed; }Copy the code
    • There are arguments:
      • function functionName($parameter 1, $parameter 2, $parameter 3) {the code to be executed; }Copy the code
  • Function names can start with a letter or underscore (instead of a number). Function names are case-sensitive
  • Call function syntax:functionName()
  • The position of the function definition can be after the function call (similar to C)
  • PHP functions do not support function overloading
  • The default values of the parameters of a PHP function can be set when the function is defined. If the parameter is not assigned a value when the function is called, the default value is used
  • When using default parameters, any default parameters must be placed to the right of any non-default parameters
    • e.g. Function fun($name, $age, $sex = "male ")
  • If the function has a return value, it needs to be used only inside the functionreturnreturns
  • The header of a function does not need to be declared