PHP Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 3.00

What Is a Function?

This section describes what is a function. A quick example is provided showing how to define and call a function.

What Is a Function? A function is a definition of a block of statements. The block of statements in a function will be executed only when the function is invoked. PHP provides a long list of built-in (predefined) functions. PHP supports user-defined functions - You define your own functions in PHP source code.

To learn how to use user-defined functions in PHP, we need to pay attentions in following areas:

1. How to define a function?

2. How to call a function to execute its statements?

3. How to pass input values into a function?

4. How to return a result from a function?

5. How to share variables with a function?

Here is a simple example script of defining a function, calling a function, passing data into a function, and returning result from a function:

   function square($x) {
      $y = $x * $x;
      return $y;
   }

   $radius = 2.0;
   $area = M_PI * square($radius);
   echo($area);

Notice that in this example script:

  • A function is defined with a "function" statement and named as "square".
  • The function is called to execute as an operand in an expression in its name.
  • One input value is passed into the function at the calling time.
  • The result is returned using the "return" statement.

Last update: 2005.

Sections in This Chapter

What Is a Function?

"function" Statements - Defining Functions

Function Call Operations

Passing Arguments to Functions

Example of Passing Arguments by Values

Using Pass-by-Value Arguments for References

Example of Passing Arguments by References

Variable-Length Argument Lists

Providing Default Values to Argument Variables

Returning Values from Functions

Returning References from Functions

Dr. Herong Yang, updated in 2009
What Is a Function?