PHP Functions

What are user-defined functions?

As you build more complex application, you may find that you use, and reuse the same blocks of code over and over again. This is a good indication that you should create a function. A function is a block of code set with an identifier, that can to be executed at some point in the future. PHP comes with 100s, if not 1000s, of built-in functions, and we have already use a few. User-defined functions are those functions you create yourself.

Creating a function

Functions are declared with the function key word, accept parameter(s), and are capable of returning a value to the calling element.

function buildParagraph( $contents ){ 
  $output = "<p>" . $contents . "</p>"; 
  return $output; 
}

This example function takes in a string parameter and sends back that same content wrapped inside an HTML paragraph tag.

Calling a function

To call that function from somewhere else in the PHP code we would do something like this:

$sample = "This is some sample text."; 
echo buildParagraph( $sample );

This sample will call the buildParagraph function and pass the value of the $sample variable to that function. The function then sends back the text from $sample, wrapped inside an HTML paragraph tag. Then that returned paragraph is output to the page.

Remember that the main purpose of PHP is to generate HTML content for your web pages.