Web Development Tutorials




  
  

Using Functions

Functions are used to break large blocks of code into smaller, more manageable units. Code contained inside of a function performs a specific task and returns a value. PHP includes two types of functions - user defined or those created by the programmer and internal (built-in) functions which are a part of the PHP language definition. This first section focuses on creating and using user defined functions.

User defined functions are created using the function keyword. User-defined functions are useful particularly in larger PHP programs because they can contain blocks of code that can be called or used in the program without having to continuously re-write the code. The following is an example of a simple PHP user defined function:

  // This is an example of a PHP function. 
  // It calculates the sum of two numbers and returns the result to the calling program
  function add_numbers($num1, $num2)
  {
	return $num1 + $num2;	
  }
  

User defined functions may be called from anywhere within a PHP code block. In PHP a function is executed by coding its name. After the function is called, it accepts any passed values in the form of parameters, performs the defined tasks, and returns a value to the calling program.

A simple example is shown below:

  <?php 
  
    function add_numbers($num1, $num2)
    {
       return $num1 + $num2;
    }
    echo "The sum of 5 and 2 is " . add_numbers(5, 2);

  ?>
  

The add_numbers() function is defined initially, however, it is not called until later in the program. The function call occurs within the echo statement. The string "The sum of 5 and 2 is " is displayed. The function name is concatenated to the string output thus calling the function. The function passes two arguments - 5 and 2. These are assigned to the function parameters $num1 and $num2. The parameters are added together and the return statement is called to "return" the value or some of the two numbers to the location in the PHP code block that initially called the function. The output is displayed below:

   The sum of 5 and 2 is 7 
   

Function names follow the same rules as variables in PHP. Valid names may begin with a letter of underscore and can be followed by any number of letters, numbers, or underscores.


TOP | NEXT: Chapter 7 - Basic Form Processing