The Headquarters Of Web

Facebook Twitter Google Plus RSS Feed Email

Creating Your Own PHP Functions - PHP MySQL Tutorials

Published on: at 2:50 PM | Posted By:

Step 1

What is a function? A function in its simplest form is a set of instructions. We call it (usually feeding data into it at the same time), and it either outputs something, performs an action or returns the result of the instructions to the script. Most of the time we use PHP's built in functions, such as md5(), explode(), preg_match()etc. But sometimes it is useful for us to create our own functions to use in the same way we do the built in functions. A function has several basic parts:
  • The identifier, this is the "name" of the function, and it is the keyword required to call the function where it is required. This can me something like myfunction, in which case the function would be called with myfunction().
  • The parameters, these are the arguments the function takes when it is called, and are listed from left to right as first, second, third parameters. For example, the function myfunction($foo,$bar) has two parameters, $foo and $bar. $foo is the first, and $bar the second.
  • The body of the function, this contains the statements that the function executes when it is called. These can be anything you wish depending on the purpose of the function.

Step 2

Why use them? User-defined Functions are a very important part of coding any sizable application, they allow the coder to write less code, and makes changes to one part of a complex program much faster and more effectively than with basic procedural code. The main reason for this is that it allows you to re-use the code that you have already written, for example, say you have an operation that takes ten lines of code to achieve each time it's called, by making this code a seperate entity and using it every time those statements are required you avoid repetition of code and thereby reduce the total number of lines more and more drastically the more times the function is required.

Step 3

To create functions we use the keyword "function". This keyword tells the PHP engine that the next block of code will be a custom function. After this we name the function, then add the parameters in brackets and then define the content of the function within curly braces. Here is an example of a custom function:


// array randarr(int $num [, int $min=0 [, int $max=100 ]])
// Create an array of integers between
// a minimum and maximum value.
function randarr($num,$min=0,$max=100) // Define the function.
   // The code within these curly braces is the body of the function.
   $arr = array(); // Create an array.
   for($i=0; $i < $num; $i++)
      $arr[] = rand($min,$max); // Add $num integers to the array.
   return $arr; // Return the array created.
   // End of function.


Step 4

Calling functions: In this example we have made a function that creates an array of random numbers, we can then call the function with randarr(), the name of the function. For example, if we saved the above code in a file called funcs.php then we might call it like so:


require_once('funcs.php'); // Include our randarr() function

$array = randarr(5,50,80); // Create an array with five integers between 50 and 80.
print_r($array); // Output our array.

/* Outputs something like this: Array ( [0] => 66 [1] => 74 [2] => 62 [3] => 52 [4] => 69 ) */


Step 5

Optional Parameters: In many cases we do not want to define all of the parameters every time we execute the function, and to facilitate this we use optional parameters. To create an optional parameter we simply assign the parameters a default value when we declare the function using the = (equals) operator. In randarr the second two parameters ($min and $max) are optional parameters, and the function can be called without them. If we wanted the function to use our default range of 0-100 then we would call the function like this:


require_once('funcs.php'); // Include our randarr() function

$array = randarr(5); // Create an array with five integers within our default range (0-100).
print_r($array);// Output our array.

Outputs something like this:
    [0] => 46
    [1] => 38
    [2] => 79
    [3] => 56
    [4] => 97


We could also call the function with only one of the optional parameters, but the first parameter is required every time you call the function. Attempts to call it without non-optional parameters will cause an error. As you can see, by placing that function in another file and using require_once() to include it into other pages we can create these arrays in two lines instead of the four it would take otherwise.

Step 6

Applications of Functions: You can apply functions to larger applications too. For example, you may require a library of common functions for a web application, and place them all in one globally included file, or extend functions into class methods with Object-Oriented coding. Once you understand functions many long and previously complex programs become simple to write and maintain. And that's all you need to know about functions :-)

No comments On "Creating Your Own PHP Functions - PHP MySQL Tutorials"

Post a Comment

Get Latest Updates

Blog Archive

Total Pageviews